如何过滤数据表中的某些DataRows

我有一个像上面那样的DataTable,过滤行的有效方法是什么

  • Col1,Col2,Col3,Col4应与其他行匹配
  • Col5不同
  • 像下面的东西,

    如何提取Col5不同的行

    谢谢


    我认为你可以使用System.Data.DataView的ToTable(distinct,columns)方法。 以下是代码示例:

    DataView view = new DataView(table);
    DataTable distinctValues = view.ToTable(true, "Col1", "Col2" ,"Col3","Col4","Col5");
    

    // DataTable dt = new DataTable(); for (int i = 1; i < 6; i++) dt.Columns.Add("Col" + i); 
    // foreach (var c in "EEFG") dt.Rows.Add(("A B C D " + c).Split());   // optional to generate the table
    
    dt = dt.Rows.Cast<DataRow>()
        .GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3]))          // group by the first 4 values in each row (you can replace the numbers with the indexes or names of your columns)
        .SelectMany(g => g.GroupBy(r => r[4], (k, v) => v.First()))  //  group each group by the 5th value, and select the first row in each group, to get the distinct rows
        .CopyToDataTable();                                          // optional to copy the rows to a new DataTable
    
    Debug.Print(string.Join("n", dt.AsEnumerable().Select(r => string.Join("t", r.ItemArray)))); // optional to print the result
    

    如果没有其他列,可以缩短它获取每个组中不同的行:

    dt = dt.Rows.Cast<DataRow>().GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3])) 
        .SelectMany(g => g.Distinct(DataRowComparer.Default)).CopyToDataTable();
    

    运行它并查看kdr

    var groups = dt.AsEnumerable().GroupBy(x => new { col1 = x["col1"], col2 = x["col2"], col3 = x["col3"], col4 = x["col4"] });
    
    foreach (var group in groups)
    {
        var k = group.Key;
    
        foreach (var dr in group)
        {
        }
    }
    
    链接地址: http://www.djcxy.com/p/68837.html

    上一篇: How to filter certain DataRows in a Data Table

    下一篇: Replace string values with LINQ