简体   繁体   中英

How to group by one member and select a second member?

When I max over years how can I select the month for which the max value belongs to?

Please consider the following code:

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

I know my problem is not quite possible in SQL but I was wondering if LINQ is more flexible here.

This is the solution. However, if there are two different Data_Point s having the same Value equal to the maximum of the year both of them returned.

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;

To have only one Data_Point (for example the first catch):

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

You can change the last line to have the Month and Year and the Max(Value) only:

   select new { grp.Year, grp.Month, MaxValueOfTheYear = grp.Month,grp.Value };
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();

First of all, in SQL you can group by one column and select other columns by using min, max, average.

In LINQ you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM