DataTable通过最大值区分行

时间:2018-09-25 06:41:29

标签: linq datatable

我只需要X和Y的不同值,但ID字段和行的最大值为P

例如,这是我的数据表

ID    X       Y     P  

03    Str1    C1    10  
04    Str1    C1    5  
05    Str1    C1    1  
06    Str1    C1    2  
07    Str2    C1    25  
08    Str2    C1    4  
09    Str1    C2    411  
10    Str1    C2    2356  
11    Str2    C2    12  
12    Str2    C2    33  

上面的DataTable的结果应该在下面。

ID    X       Y     P  

03    Str1    C1    10  
07    Str2    C1    25  
10    Str1    C2    2356  
12    Str2    C2    33  

2 个答案:

答案 0 :(得分:0)

public class Table
    {
        public string ID { get; set; }
        public string X { get; set; }
        public string Y { get; set; }
        public int P { get; set; }
    }

List<Table> table = new List<Table>() {
                    new Table() { ID = "03", X = "Str1", Y = "C1", P = 10 },
                    new Table() { ID = "04", X = "Str1", Y = "C1", P = 5 },
                    new Table() { ID = "05", X = "Str1", Y = "C1", P = 1 },
                    new Table() { ID = "06", X = "Str1", Y = "C1", P = 2 },
                    new Table() { ID = "07", X = "Str2", Y = "C1", P = 25 },
                    new Table() { ID = "08", X = "Str2", Y = "C1", P = 4 },
                    new Table() { ID = "09", X = "Str1", Y = "C2", P = 411 },
                    new Table() { ID = "10", X = "Str1", Y = "C2", P = 2356 },
                    new Table() { ID = "11", X = "Str2", Y = "C2", P = 12 },
                    new Table() { ID = "12", X = "Str2", Y = "C2", P = 33 },
                };

            var ret = table.GroupBy(p => new { p.X, p.Y }).Select(i => new { Table = new Table() { X = i.Key.X, Y = i.Key.Y, P = i.Max(o => o.P) }, Items = i.Select(f => f) }).ToList();
            ret.ForEach(c => c.Table.ID = c.Items.First(i => i.P == c.Table.P).ID);

            var finalResult = ret.Select(x => x.Table).ToList();

答案 1 :(得分:0)

dt.AsEnumerable()。OrderBy(row => row [“ X”])。ThenByDescending(row => row [“ Y”])。GroupBy(row => new {a = row [“ X”] ,b = row [“ Y”]})。Select(group => group.First())。CopyToDataTable();