【问题标题】:DataTable distinct rows by max valueDataTable 按最大值区分行
【发布时间】:2018-10-01 20:09:25
【问题描述】:

我只需要 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  

上述数据表的结果应该如下。

ID    X       Y     P  

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

【问题讨论】:

  • 那么你有什么尝试吗?结果如何?
  • dataTable.DefaultView.ToTable(true, "X","Y"); 上面的语句做了不同的但它在新的DataTable中只复制了这两列。

标签: linq datatable


【解决方案1】:
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();

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多