Linq distinct & max

前端 未结 4 914
猫巷女王i
猫巷女王i 2021-01-04 11:50

I have to query this table:

symbol    time
------    ----------
aaa       2013-04-18 09:10:28.000    
bbb       2013-04-18 09:10:27.000    
aaa       2013-04         


        
相关标签:
4条回答
  • 2021-01-04 12:09

    try out this

    var q = MyTable.GroupBy(x => x.symbol )
                   .Select(g => g.OrderByDescending(i => i.time).First());
    

    or use max like this

     var data = from r in MyTable
                       group r by r.symbol into g
                       select new { name= g.Key, data= g.Max(a=>a.time) };
    
    0 讨论(0)
  • 2021-01-04 12:20

    u can use lambda expression with Linq -

    var result= (from li in List.Distinct().OrderByDescending(x => x.time)
                           select li).FirstOrDefault();
    
    0 讨论(0)
  • 2021-01-04 12:22

    I would actually use.

    void Main()
    {
        var set = new [] {
            new Foo{A = "aaa", B = 1},
            new Foo{A = "bbb", B = 2},
            new Foo{A = "aaa", B = 3},
            new Foo{A = "bbb", B = 4},
        };
    
        var result = from x in set
                    group x.B by x.A into g
                    select new {id = g.Key, biggest = g.Max()};
    
        Console.WriteLine(result);
    }
    
    0 讨论(0)
  • 2021-01-04 12:25

    Group rows by symbol and then select from each group item with max time (Table is your database table name from context):

    from r in Table
    group r by r.symbol into g
    select g.OrderByDescending(x => x.time).First()
    

    Same with method syntax:

    Table.GroupBy(r => r.symbol)
         .Select(g => g.OrderByDescending(x => x.time).First());
    
    0 讨论(0)
提交回复
热议问题