- Source Data
- 使用
DataView
去重 - 使用Lambda表达式去重
1. 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);
2. 使用DataView
去重
DataView dv = dtSource.DefaultView;
dv.Sort = "UserID ASC";
DataTable distinctDT = dv.ToTable("NewData", true, new string[] { "UserID", "UserName", "Stage" });
3. 使用Lambda表达式去重
DataTable distinctDT = dtSource.Clone();
var distinctRows = dtSource.AsEnumerable().Cast<DataRow>()
.Select(row => new
{
UserID = row.Field<string>("UserID"),
UserName = row.Field<string>("UserName"),
Stage = row.Field<string>("Stage"),
}).Distinct();
if (distinctRows.ToList().Count > 0)
{
distinctRows.ToList().ForEach(q =>
{
DataRow dr1 = distinctDT.NewRow();
dr1["UserID"] = q.UserID;
dr1["UserName"] = q.UserName;
dr1["Stage"] = q.Stage;
distinctDT.Rows.Add(dr1);
});
}
原文地址:https://www.cnblogs.com/LuckyZLi/p/12558802.html
时间: 2024-10-09 22:00:07