高效过滤数据表

发布于 2024-12-22 12:31:20 字数 419 浏览 3 评论 0原文

过滤数据表中数据行的最有效方法是什么?我有一个整数列表,想要检索与列表中的整数匹配的所有行(并最终从中创建一个数据表)。我目前正在使用下面的代码,但速度很慢。我是否缺少更有效的方法?

foreach (var i in integerlist)
{
     DataRow dr = (from row in originalDataTable.AsEnumerable()
                   where row.Field<int>("urlID") == i
                   select row).FirstOrDefault<DataRow>();

     if (dr!= null)
     {
          newDataTable.Rows.Add(dr);
     }
}

What's the most efficient way of filtering DataRows in a DataTable? I have a list of integers and want to retrieve all rows (and eventually create a DataTable from them) which match the integers in the list. I'm currently using the code below, but it's quite slow. Am I missing a more efficient way?

foreach (var i in integerlist)
{
     DataRow dr = (from row in originalDataTable.AsEnumerable()
                   where row.Field<int>("urlID") == i
                   select row).FirstOrDefault<DataRow>();

     if (dr!= null)
     {
          newDataTable.Rows.Add(dr);
     }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

世界等同你 2024-12-29 12:31:20

我建议你尝试反之亦然。

foreach (var row in originalDataTable)
{

    if(integerList.Contains( (int)row["urlID"]))
       newDataTable.ImportRow(row)
}

如果数据集中的行数比 int 集合中的整数多,则更有意义。
希望它有帮助:)

I suggest you to try to do vice versa.

foreach (var row in originalDataTable)
{

    if(integerList.Contains( (int)row["urlID"]))
       newDataTable.ImportRow(row)
}

It makes even more sense if you have more rows in dataset then integers in your int collection.
Hope it helps :)

一个人的夜不怕黑 2024-12-29 12:31:20

嗯...可能我错过了一些东西,但是...

使用 DataView 并应用 RowFilter 吗?

Hm... may be I'm missing something, but...

Woudn't be it easier just use DataView and apply a RowFilter for it ?

你如我软肋 2024-12-29 12:31:20

您可以尝试进行连接,例如:

var resultSet = 
from row in originalDataTable.AsEnumerable()
join i in integerlist
on row.Field<int>("urlID") equals i
select row;

这应该为您提供完整的结果集。
如果你需要一个数据表,你可以这样做:

resultSet.CopyToDataTable();

you could try doing a join such as:

var resultSet = 
from row in originalDataTable.AsEnumerable()
join i in integerlist
on row.Field<int>("urlID") equals i
select row;

that should give you the full result set.
if you need a datatable you could do:

resultSet.CopyToDataTable();

缪败 2024-12-29 12:31:20

正如@Tigran所说,您可以使用数据视图,请检查 这篇 msdn 文章介绍了如何实现这一目标。

基本上,您使用 DataView 来过滤数据,然后调用 DataView.ToTable 方法来获取新的 DataTable。

As @Tigran says you can use the dataview, check this msdn article on how to accomplish just that.

Basically you use a DataView to filter the data and the you call the DataView.ToTable method to get the new DataTable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文