我有一个包含 22 列的数据表,其中一列称为“id”。我想查询此列并将所有不同的值保留在列表中。该表可以包含 10 到 100 万行。
执行此操作的最佳方法是什么?目前我正在使用 for 循环遍历列并比较值,如果值相同则转到下一个,如果不相同则将 id 添加到数组中。但是由于表可以有 10 到 100 万行,有没有更有效的方法来做到这一点!我将如何更有效地执行此操作?
最佳答案
方法一:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "id");
方法二: 您将必须创建一个与您的数据表列名称匹配的类,然后您可以使用以下扩展方法将 Datatable 转换为 List
public static List<T> ToList<T>(this DataTable table) where T : new()
{
List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (row.Table.Columns.Contains(property.Name))
{
if (row[property.Name] != DBNull.Value)
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
然后您可以使用
与列表区分开来 YourList.Select(x => x.Id).Distinct();
请注意,这将为您返回完整的记录,而不仅仅是 ID。
关于c# - 从大型 DataTable 列中选择不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17466253/