C# Distinct去重DataTable

2021-03-13 03:28

阅读:265

标签:code   tin   new   opp   stage   表达式   pop   ima   ack   

  • 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. 使用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()
					.Select(row => new
					{
						UserID = row.Field("UserID"),
						UserName = row.Field("UserName"),
						Stage = row.Field("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);
	});
}

技术图片

C# Distinct去重DataTable

标签:code   tin   new   opp   stage   表达式   pop   ima   ack   

原文地址:https://www.cnblogs.com/LuckyZLi/p/12558802.html


评论


亲,登录后才可以留言!