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

前端 未结 6 734
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2021-01-03 10:23

    I was solving the same situation and found it quite interesting and would like to share my finding.

    1. If rows are to be distinct based on ALL COLUMNS.
    DataTable newDatatable = dt.DefaultView.ToTable(true, "ID", "Name", "DateBirth");
    

    The columns you mention here, only those will be returned back in newDatatable.

    1. If distinct based on one column and column type is int then I would prefer LINQ query.
      DataTable newDatatable = dt.AsEnumerable()
                               .GroupBy(dr => dr.Field("ID"))
                               .Select(dg => dg).Take(1)
                               .CopyToDataTable();
    
    1. If distinct based on one column and column type is string then I would prefer loop.
    List toExclude = new List();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        var idValue = (string)dt.Rows[i]["ID"];
        if (toExclude.Contains(idValue))
        {
            dt.Rows.Remove(dt.Rows[i]);
            i--;
        }
        toExclude.Add(glAccount);
    }
    

    Third being my favorite.

    I may have answered few things which are not asked in the question. It was done in good intent and with little excitement as well.

    Hope it helps.

提交回复
热议问题