简体   繁体   English

在C#中过滤DataTable

[英]Filter DataTable in c#

I have a datatable like: 我有一个像这样的数据表:

    ID | ID2
    --------
    1  |  2
    1  |  3
    12 |  2 
    15 |  3

I need to filter data table with ID2(I know two ID2 values in this case 2 and 3) in such a way that i should get output as 我需要以这种方式过滤ID2的数据表(在这种情况下,我知道两个ID2值2和3),这样我应该得到输出

    ID | ID2
    --------
    1  |  2
    1  |  3

That means ID which have two ID2(2 and 3) should be selected. 这意味着应选择具有两个ID2(2和3)的ID。

dt.Select("ID2=2 AND ID2=3"); dt.Select(“ ID2 = 2 AND ID2 = 3”); is not working in this case. 在这种情况下不起作用。

Thanks 谢谢

It is not clear what are you searching for. 目前尚不清楚您要搜索什么。
If you want to extract all the rows in which the same value for the ID column appears two or more times then 如果要提取ID列的相同值出现两次或多次的所有行,则

DataRow[] rows = dt.Select("Count(ID) > 1)") DataRow []行= dt.Select(“ Count(ID)> 1)”)

You were right, this doesn't work on a datatable without relationships. 您是对的,如果没有关系,这对数据表将不起作用。
I have found a solution usig Linq, 我找到了解决方案usig Linq,

// Returns an IGrouping<int,DataRow> for every ID that appears more than one time
var result = dt.AsEnumerable().GroupBy(z => z.Field<int>("ID"))
             .Select(q=> new{Count = q.Count(), ID=q.Key})
             .Where(x => x.Count > 1);

// Now we could extract the rows in the usual way
foreach(var l in result)
{
    DataRow[] r = dt.Select("ID=" + l.ID);
    r.Dump();
}

I don't know how efficient is this, but at least this seems to work 我不知道这有多有效,但至少这似乎有效

You can use LINQ to DataSet 您可以使用LINQ to DataSet

var rows = table.AsEnumerable().Where(r => r.Field<int>("ID") == 1);             

BTW according to desired result you should filter by ID . 顺便说一句,根据所需结果,您应该按ID过滤。

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

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