C# - Remove rows with the same column value from a DataTable

前端 未结 6 748
深忆病人
深忆病人 2021-01-03 09:40

I have a DataTable which looks like this:

 ID   Name    DateBirth
.......................
 1     aa      1.1.11
 2     bb      2.3.11
 2     cc          


        
6条回答
  •  不知归路
    2021-01-03 10:31

    Not necessarily the most efficient approach, but maybe the most readable:

    table = table.AsEnumerable()
        .GroupBy(row => row.Field("ID"))
        .Select(rowGroup => rowGroup.First())
        .CopyToDataTable();
    

    Linq is also more powerful. For example, if you want to change the logic and not select the first (arbitrary) row of each id-group but the last according to DateBirth:

    table = table.AsEnumerable()
        .GroupBy(row => row.Field("ID"))
        .Select(rowGroup => rowGroup
                              .OrderByDescending(r => r.Field("DateBirth"))
                              .First())
        .CopyToDataTable();
    

提交回复
热议问题