C# Distinct去重DataTable

时间:2024-02-01 18:39:14

C# Distinct去重DataTable

  • 使用DataView去重
  • 使用Lambda表达式去重

Source Data

DataTable dtSource = new DataTable();
dtSource.Columns.Add("UserID", System.Type.GetType("System.String"));
dtSource.Columns.Add("UserName", System.Type.GetType("System.String"));
dtSource.Columns.Add("Stage", System.Type.GetType("System.String"));
DataRow dr = dtSource.NewRow();
for (int i = 0; i < 2; i++)
{
    dr[0] = "0000";
    dr[1] = "Lucky";
    dr[2] = "AA";
    dtSource.Rows.Add(dr.ItemArray);
}
dr[0] = "1111";
dr[1] = "Poppy";
dr[2] = "AB";
dtSource.Rows.Add(dr.ItemArray);
dr[0] = "2222";
dr[1] = "Zack";
dr[2] = "AC";
dtSource.Rows.Add(dr.ItemArray);                

1. 使用DataView去重

DataView dv = dtSource.DefaultView;
dv.Sort = "UserID ASC";
DataTable distinctDT = dv.ToTable("NewData", true, new string[] { "UserID", "UserName", "Stage" });