实体类
public class Movie
{public string Name { get; set; }public string Area { get; set; }public DateTime ProductTime { get; set; }
}
初始化数据
public static List<Movie> InitData()
{List<Movie> data = new List<Movie>(){new Movie(){ Name="功夫",Area="中国香港",ProductTime=new DateTime(2004, 12, 23) },new Movie(){ Name="无间道",Area="中国香港",ProductTime=new DateTime(2002, 12, 12) },new Movie(){ Name="霍元甲",Area="中国大陆",ProductTime=new DateTime(2006, 01, 25) },new Movie(){ Name="我不是药神",Area="中国大陆",ProductTime=new DateTime(2018, 07, 05) },new Movie(){ Name="让子弹飞",Area="中国大陆",ProductTime=new DateTime(2010, 12, 16) },new Movie(){ Name="肖申克的救赎",Area="美国",ProductTime=new DateTime(1994, 09, 10) },new Movie(){ Name="阿甘正传",Area="美国",ProductTime=new DateTime(1994, 07, 06) },new Movie(){ Name="蜘蛛侠2",Area="美国",ProductTime=new DateTime(2004, 06, 30) },};return data;
}
方式一
static void Main(string[] args){List<Movie> data = InitData();var groupData = data.OrderByDescending(a => a.ProductTime).GroupBy(a => a.Area).Select(group => new{Area = group.Key,Name = group.FirstOrDefault().Name,ProductTime = group.FirstOrDefault().ProductTime});foreach (var item in groupData){Console.WriteLine($"电影名称:{item.Name},上映地区:{item.Area},上映时间:{item.ProductTime.ToString("yyyy-MM-dd")}");}}
方式二
static void Main(string[] args){List<Movie> data = InitData();var groupData = data.GroupBy(a => a.Area).Select(group => group.OrderByDescending(item=>item.ProductTime).FirstOrDefault());foreach (var item in groupData){Console.WriteLine($"电影名称:{item.Name},上映地区:{item.Area},上映时间:{item.ProductTime.ToString("yyyy-MM-dd")}");}}
方式三
static void Main(string[] args)
{List<Movie> data = InitData();var groupData = from item in dataorderby item.ProductTime descendinggroup item by item.Area into groupdataselect groupdata.FirstOrDefault();foreach (var item in groupData){Console.WriteLine($"电影名称:{item.Name},上映地区:{item.Area},上映时间:{item.ProductTime.ToString("yyyy-MM-dd")}");}
}