2013-01-24 58 views
5

Tôi đang cố tạo bộ sưu tập cặp KeyValue với biểu thức lambda.KeyValuePair trong biểu thức Lambda

Đây là lớp của tôi và bên dưới là mã lambda của tôi. Tôi không thể tạo KeyValuePair.

Tôi muốn để có được một bộ sưu tập của KeyValuePair của Id, IsReleased cho phim hài. Tôi đặt KeyValuePair trong HashSet để tìm kiếm nhanh.

public class Movie{ 
    public string Name{get;set;} 
    public int Id{get;set;} 
    public bool IsReleased{get;set;} 
    //etc 
} 

List<Movie> movieCollection=//getting from BL 

var movieIdReleased= new 
HashSet<KeyValuePair<int,bool>>(movieCollection.Where(mov=> mov.Type== "comedy") 
            .Select(new KeyValuePair<int,bool>(????)); 
+0

Cân nhắc usin lớp từ điển thay vì HashSet ở đây, tôi đoán nó là thích hợp hơn ở đây. –

+0

Một _HasSet_ của _KeyValuePair_ có chứa ID phim ?! Bạn có thể giải thích những gì bạn muốn làm không? –

Trả lời

8

Bạn nên vượt qua lambda vào rằng phương pháp .Select, không chỉ biểu hiện:

.Select(movie => new KeyValuePair<int,bool>(movie.Id, movie.IsReleased)) 

hy vọng rằng sẽ giúp!

2
//.Select(new KeyValuePair<int,bool>(????)); 
.Select(movie => new KeyValuePair<int,bool>() 
       { Key = movie.Id, Value = movie.IsReleased}); 
+0

Có. Những công việc này. Cảm ơn. Tôi quên thêm exp =>. –

1
var comedyMovies = movieCollection 
    .Where(mc => "comedy".Equals(mc.Type, StringComparison.OrdinalIgnoreCase)) 
    .Select(mc => new KeyValuePair<int, bool>(mc.Id, mc.IsReleased)); 
var distinctComedyMovies = new HashSet<KeyValuePair<int,bool>>(comedyMovies);