假设我有一节课
public class Movie
{
public string Title { get; set; }
public string Genre { get; set; }
public int Rating { get; set; }
}
和一个电影文本文件,它将被解析成一个列表
The_Godfather Action 96
The_Dark_Knight Drama 24
Cleopatra Comedy 61
Sabotage Action 88
Inception Drama 86
The_Matrix Comedy 14
Life_Is_Beautiful Drama 19
City_of_God Horror 12
Raven Comedy 30
Breaking_Wind Comedy 59
City_Lights Documentary 46
Born_Wild Drama 55
和一个函数
public static Dictionary<string, Movie> HighestRatingForEachGenre(List<Movie> movies)
我想使用LINQ for each 流派返回最高评级.
我想按流派分组,然后返回每个流派的标题和电影对象.
我可以用Foreach循环很容易地做到这一点.
我仍然是LINQ的新手,不知道go 哪里找.
基本方法
Dictionary<string, Movie> result = new Dictionary<string, Movie>();
foreach (Movie movie in movies)
{
if (result.ContainsKey(movie.Genre))
{
if (result[movie.Genre].Rating < movie.Rating) result.Remove(movie.Genre);
else continue;
}
result.Add(movie.Genre, movie);
}
return result;