c# - 从大型 DataTable 列中选择不同的值

标签 c# datatable

我有一个包含 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/

相关文章:

c# - 如何使用 Moq 框架模拟一个简单的方法?

c# - DataTable 的替代数据结构

c# - 在 C# 中获取数据表中所有重复行的计数

c# - 线程被中止 C#

C# web api Swagger 集成

c# - 数据表添加数据行时出现错误[]

java - 向 h :dataTable via AJAX with request-scoped bean without losing the row data 添加一行

c# - 在数据表上使用通用列表会减少性能开销吗?

c# - 在 formFlow 中添加验证步骤 - 检查浇头是否有货

c# - 是否可以从默认表 AspNetUsers 中删除行?如果是,请解释一下