What is the best way to remove duplicates from a datatable?

前端 未结 12 2074
醉酒成梦
醉酒成梦 2021-01-02 13:23

I have checked the whole site and googled on the net but was unable to find a simple solution to this problem.

I have a datatable which has about 20 columns and 10K

12条回答
  •  灰色年华
    2021-01-02 14:07

    I think this must be the best way to remove duplicates from Datatable by using Linq and moreLinq Code:

    Linq

    RemoveDuplicatesRecords(yourDataTable);
    
    
    private DataTable RemoveDuplicatesRecords(DataTable dt)
    {
        var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
        DataTable dt2 = UniqueRows.CopyToDataTable();
        return dt2;
    }
    

    Blog Article : Remove Duplicate rows records from DataTable Asp.net c#


    MoreLinq

    // Distinctby  column name ID 
    var valueDistinctByIdColumn = yourTable.AsEnumerable().DistinctBy(row => new { Id = row["Id"] });
    DataTable dtDistinctByIdColumn = valueDistinctByIdColumn.CopyToDataTable();
    

    Note: moreLinq need to add library.

    In morelinq you can use function called DistinctBy in which you can specify the property on which you want to find Distinct objects.

    Blog article : Using moreLinq DistinctBy method to remove duplicate records

提交回复
热议问题