Lambda表达式中的KeyValuePair

时间:2013-01-24 14:57:58

标签: c# lambda keyvaluepair

我正在尝试使用lambda表达式创建KeyValue对集合。

这是我的班级,下面是我的lambda代码。我没能创建KeyValuePair。

  

我想获得一个Id的KeyValuePair集合,IsReleased for    喜剧电影。我将这些KeyValuePair放在HashSet中进行快速搜索

 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>(????));

3 个答案:

答案 0 :(得分:8)

你应该将lambda传递给.Select方法,而不仅仅是表达式:

.Select(movie => new KeyValuePair<int,bool>(movie.Id, movie.IsReleased))
希望有所帮助!

答案 1 :(得分:2)

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

答案 2 :(得分: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);