C# 对DataTable 的某一列进行去重,并保留其他列,其他列不去重(转)

可以使用 LINQ 来对 DataTable 的某一列进行去重操作,并同时保留其他列。以下是一个示例代码:

using System;
using System.Data;
using System.Linq;

class Program
{
static void Main()
{
// 创建一个示例的 DataTable
DataTable table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Age", typeof(int));

table.Rows.Add(1, "Alice", 25);
table.Rows.Add(1, "Bob", 30);
table.Rows.Add(1, "Alice", 28);
table.Rows.Add(1, "Charlie", 35);
table.Rows.Add(1, "Bob", 32);

// 对 Name 列进行去重
var distinctRows = table.AsEnumerable()
.GroupBy(row => row.Field<string>("Name"))
.Select(group => group.First());

// 创建一个新的 DataTable 存储去重后的结果
DataTable distinctTable = table.Clone();
foreach (var row in distinctRows)
{
distinctTable.ImportRow(row);
}

// 输出去重后的结果
foreach (DataRow row in distinctTable.Rows)
{
Console.WriteLine($"{row["Id"]}\t{row["Name"]}\t{row["Age"]}");
}
}
}


原文链接:https://blog.csdn.net/m0_60580105/article/details/132587811

posted on 2024-06-14 10:15  xihong  阅读(9)  评论(0编辑  收藏  举报

导航