使用 LINQ 从 DataSet 中选择 Rows,其中 RowsID 的列表位于 List<T> [英] Select Rows from a DataSet using LINQ, where the list of RowsID's are in a List<T>

查看:14
本文介绍了使用 LINQ 从 DataSet 中选择 Rows,其中 RowsID 的列表位于 List<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我必须说,我是使用 LINQ 的新手.实际上我以前从未使用过,但我有一个任务需要过滤 DataTable,使用来自列表的值.所以我想知道在 LINQ 中是否可以使用列表中的值作为过滤器值来查询数据表.有人可以给我一些提示

First I have to say, that I am a newby using LINQ. Actually I never used before, but I am having a task where I need to filter a DataTable, using values that will come from a List. So I will like to know if it's possible in LINQ to query on a Datatable using values in the List as Filter values. Some one can give me some hint's

谢谢.

推荐答案

执行此操作的最佳方法取决于您打算如何处理过滤后的结果.您是否需要将结果作为 DataTable 返回以进行进一步操作,或者您是否需要对结果进行数据绑定?

The best way to do this depends on what you plan to do with the filtered results. Do you need the results back as DataTable for further operations, or are you databinding to the results?

以下面的示例为例,它返回匹配 DataRows 的(可绑定的)枚举器

Take the example below, which returns a (bindable) enumerator of matching DataRows

//create sample table with sample rows
DataTable table = new DataTable();

table.Columns.Add("id", typeof(int));

for (int i = 1; i < 11; i++)
{
    DataRow row = table.NewRow();
    row[0] = i;
    table.Rows.Add(row);
}

//filter the table by id (in a list)
List<int> rowIds = new List<int> { 1, 3, 6 };

IEnumerable<DataRow> matchingRows = from DataRow row in table.Rows
                   where rowIds.Contains((int)row[0])
                   select row;

如果您需要 DataTable,您可以将行导入另一个表:

If you need a DataTable you could import the rows into another table:

DataTable filteredTable = table.Clone();

foreach (DataRow filteredRow in matchingRows)
{
    filteredTable.ImportRow(filteredRow);
}

这篇关于使用 LINQ 从 DataSet 中选择 Rows,其中 RowsID 的列表位于 List&lt;T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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