简体   繁体   English

将DataRow集合与List <T>进行比较

[英]Compare DataRow collection to List<T>

I have a List<string> and I have a DataTable. 我有一个List<string> ,我有一个DataTable。

One of the columns in a DataRow is ID. DataRow中的一列是ID。 The List holds instances of this ID. List包含此ID的实例。

The DataTable gets populated on a Timer. DataTable将填充在Timer上。

I want to return items from the List that are not in the DataTable into another list. 我想将列表中不在DataTable中的项目返回到另一个列表中。

You will want to do something like this 你会想做这样的事情

var tableIds = table.Rows.Cast<DataRow>().Select(row => row["ID"].ToString());

var listIds = new List<string> {"1", "2", "3"};

return listIds.Except(tableIds).ToList();

You can cast the rows in the data table to be an IEnumerable collection and then select the "ID" column value from each of them. 您可以将数据表中的行转换为IEnumerable集合,然后从每个行中选择“ID”列值。 You can then use the Enumerable.Except extension method to get all of the values from the List that are not in the collection you just made. 然后,您可以使用Enumerable.Except扩展方法从List中获取不在您刚刚创建的集合中的所有值。

If you need to get the values that are in the table but not the list, just reverse listIds and tableIds. 如果需要获取表中的值而不是列表中的值,只需反转listIds和tableIds。

If your table was something like that: 如果你的表是这样的:

DataTable dt = new DataTable();
dt.Columns.Add("ID");
DataRow dr = dt.NewRow();
dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
dr["ID"] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = "3";
dt.Rows.Add(dr);

and the list was something like this: 列表是这样的:

List<string> ls = new List<string>{"1","2","4"};

we could get the items found in the list and not in the datatable this way: 我们可以通过这种方式获取列表中找到的项目而不是数据表中的项目:

var v = from r in ls
                where !dt.Rows.Contains(r)
                select r;
        v.ToList();

With reasonable efficiency via HashSet<T> (and noting that the fastest way to get data out of a DataRow is via the DataColumn indexer): 通过HashSet<T>以合理的效率(并注意到从DataRow获取数据的最快方法是通过DataColumn索引器):

        HashSet<int> ids = new HashSet<int>();
        DataColumn col = table.Columns["ID"];
        foreach (DataRow row in table.Rows)
        {
            ids.Add((int)row[col]);
        }
        var missing = list.Where(item => !ids.Contains(item.ID)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM