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# - 在机器上没有安装 PFX 的情况下使用客户端证书发出 HTTP 请求?

c# - 如何将 DataTable 行移动到其 DataTable 的第一个位置

c# - IIS 7's custom redirection doesn' t 传递 If-Modified-Since header 。漏洞?

c# - Windows 服务

c# - 无法更改关系,因为一个或多个外键属性不可为空

C# 使用用户输入来选择要从中随机打印元素的字符串数组

javascript - 如何遍历 DataTable 中的特定列?

javascript - 如何使用 md-order-by 属性对 md-data-table 上的日期列进行排序

vb.net - 根据 DataTable 行获取 BindingSource 位置

java - Primefaces dataTable 分页器 header 未调整