如何按一个成员分组并选择第二个成员?

时间:2013-10-27 16:22:19

标签: c# linq

当我超过多年时,如何选择最大值所属的月份?

请考虑以下代码:

public class Data_Point
{
    public int Month { get; set; }
    public int Year { get; set; }
    public int Value { get; set; }
}

static void Main(string[] args)
{
    List<Data_Point> Data = new List<Data_Point>();
    Data.Add(new Data_Point() { Month = 0, Year = 0, Value = 99 });
    Data.Add(new Data_Point() { Month = 1, Year = 0, Value = 69 });

    // Max should relate to one record only.
    var Max_Year = (from e in Data
                    group e by e.Year into y
                    select new { Month( e => e.Month ), Year = y.Key, Value = y.Max(e => e.Value) }).ToList();
}

我知道我的问题在SQL中不太可能,但我想知道LINQ在这里是否更灵活。

3 个答案:

答案 0 :(得分:1)

这是解决方案。但是,如果有两个不同的Data_Point具有相同的Value等于一年中的最大值,则两者都返回。

var Max_Year =
           from d in Data
           group d by d.Year into grouped_by_year
           let maxOfYear = grouped_by_year.Max(p => p.Value)
           from grp in grouped_by_year
           where grp.Value == maxOfYear
           select grp;

只有一个Data_Point(例如第一个捕获):

var Max_Year =
            from d in Data
            group d by d.Year into grouped_by_year
            select grouped_by_year.OrderByDescending(p=>p.Value).First();

您可以将最后一行更改为仅MonthYear以及Max(Value)

   select new { grp.Year, grp.Month, MaxValueOfTheYear = grp.Month,grp.Value };

答案 1 :(得分:0)

var Max_Year = (from e in Data
                group e by e.Year into y
                select new { Month = y.OrderByDescending(d => d.Value).First().Month, Year = y.Key, Value = y.Max(e => e.Value) }).ToList();

答案 2 :(得分:0)

首先,在SQL中,您可以按一列分组,并使用min,max,average选择其他列。

在LINQ中你可以这样做:

var maxMonthPerYear = Data
    .GroupBy(d => d.Year)
    .Select(grp => new { Y = grp.Key, M = grp.Max(grp => grp.Month) });