从大型DataTable列中选择不同的值 [英] Select distinct values from a large DataTable column

查看:92
本文介绍了从大型DataTable列中选择不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含22列的DataTable,而我拥有的一列称为 id。我想查询此列,并将所有不同的值保留在列表中。该表可以包含10到一百万行。

I have a DataTable with 22 columns and one of the columns I have is called "id". I would like to query this column and keep all the distinct values in a list. The table can have between 10 and a million rows.

执行此操作的最佳方法是什么?目前,我正在使用for循环遍历该列并比较值,如果值相同,则转到下一个,如果不相同,则将id添加到数组。但是由于表可以有10到一百万行,因此有一种更有效的方法!我如何才能更有效地做到这一点?

What is the best method to do this? Currently I am using a for loop to go though the column and compare the values and if the values are the same then the it goes to the next and when not the same it adds the id to the array. But as the table can have 10 to a million rows is there a more efficient way to do this! How would I go about doing this more efficiently?

推荐答案

方法1:

   DataView view = new DataView(table);
   DataTable distinctValues = view.ToTable(true, "id");

方法2:
您将必须创建一个类匹配您的数据表列名,然后可以使用以下扩展方法将数据表转换为列表

Method 2: You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to 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。

Please note that this will return you complete Records and not just ids.

这篇关于从大型DataTable列中选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆