可以使用 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"]}");
}
}
}
在上面的示例中,我们首先使用 LINQ 的 GroupBy 方法对 Name 列进行分组,然后使用 Select 方法选择每个组中的第一行,即实现了去重操作。最后,我们将去重后的行导入到一个新的 DataTable 中,并输出结果。
请注意,在示例中使用了 table.Clone() 方法来创建与原始 DataTable 结构相同的新 DataTable,以便存储去重后的结果。