6

我有一个List<string>,我有一个数据表。

DataRow 中的一列是 ID。List 包含此 ID 的实例。

DataTable 在 Timer 上填充。

我想将列表中不在 DataTable 中的项目返回到另一个列表中。

4

3 回答 3

15

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. 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.

If you need to get the values that are in the table but not the list, just reverse listIds and tableIds.

于 2010-01-05T11:28:12.497 回答
1

通过合理的效率HashSet<T>(并注意从 a 中获取数据的最快方法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();
于 2010-01-05T12:56:38.650 回答
1

如果你的桌子是这样的:

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);

清单是这样的:

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

我们可以通过这种方式获取列表中而不是数据表中的项目:

var v = from r in ls
                where !dt.Rows.Contains(r)
                select r;
        v.ToList();
于 2010-01-05T12:17:47.813 回答