使用LINQ从子列表中选择最大值

时间:2010-12-03 10:41:15

标签: c# linq

如何编写LINQ查询,该查询将返回“Value”类型的行,其中包含该日期的Max Date和Max值。它应该是name =“Correct”的行

我最后写了一个查询,它正在运行,只是试图找到一种正确的方法。

提前致谢

public class MeasurePoint
{
    public int No { get; set; }
    public string Weight { get; set; }
    public List<Values> Vals { get; set; }
}

public class Values
{
    public string Name { get; set; }
    public int Val { get; set; }
    public DateTime Date { get; set; }
}

public static class Test
{
    public static void Calc()
    {
        var mps = new List<MeasurePoint>();

        mps.Add(new MeasurePoint()
        {
            No = 1,
            Vals = new List<Values>()
            {
                new Values(){Date = DateTime.Now.Date.AddDays(1), Name = "testas", Val = 1},
                new Values(){Date = DateTime.Now.Date.AddDays(2), Name = "testas", Val = 5},
                new Values(){Date = DateTime.Now.Date, Name = "testas", Val = 15}
            }});
        mps.Add(new MeasurePoint()
        {
            No = 2,
            Vals = new List<Values>()
            {
                new Values(){Date = DateTime.Now.Date, Name = "testas", Val = 11},
                new Values(){Date = DateTime.Now.Date.AddDays(2), Name = "Correct", Val = 55},
                new Values(){Date = DateTime.Now.Date, Name = "testas", Val = 15}
            }
        });
        mps.Add(new MeasurePoint()
        {
            No = 3,
            Vals = new List<Values>()
            {
                new Values(){Date = DateTime.Now.Date.AddDays(1), Name = "testas", Val = 111},
                new Values(){Date = DateTime.Now.Date.AddDays(2), Name = "testas", Val = 52},
                new Values(){Date = DateTime.Now.Date, Name = "testas", Val = 15}
            }
        });

        mps.Add(new MeasurePoint()
        {
            No = 4,
            Vals = new List<Values>()                      
        });

        var x = mps.ElementAt(0).Vals.Union(mps.ElementAt(1).Vals).Union(mps.ElementAt(2).Vals);
        var z = x.Where(p => p.Date == x.Max(d => d.Date)).MaxBy(t=>t.Val);

        //One more way I've found
        var ttt = mps.SelectMany(p => p.Vals).GroupBy(t=>t.Date).MaxBy(r=>r.Key).MaxBy(g=>g.Val);
    }

3 个答案:

答案 0 :(得分:5)

var max = mps.SelectMany(x => x.Vals)
    .Aggregate((a, x) => (x.Date > a.Date) ||
                         ((x.Date == a.Date) && (x.Val > a.Val)) ? x : a);

答案 1 :(得分:2)

试试这个

var result = mps.Where(m => m.Vals.Count > 0)
    .SelectMany(m => m.Vals
        .OrderByDescending(v => v.Date)
        .Take(1), (m, v) => new {m.No, v.Date, v.Name, v.Val});

编辑 - 这是一个新版本,因为问题变得更加清晰

var result = mps.Where(m => m.Vals.Count > 0)
    .SelectMany(m => m.Vals)
    .OrderByDescending(v => v.Date)
    .ThenByDescending(v => v.Val).Take(1);

答案 2 :(得分:0)

如果MaxBy()同时IObservable<T> GroupBy()返回IEnumerable<T>,则如何使用{{1}}来调用?{/ p>