使用LINQ查询数据表的帮助 [英] Help with querying a DataTable using LINQ

查看:79
本文介绍了使用LINQ查询数据表的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下初始代码:

Suppose I have this initial code:

        DataTable table = new DataTable();
        table.Columns.Add("column1", typeof(int));
        table.Columns.Add("column2", typeof(int));
        table.Columns.Add("column3", typeof(string));
        table.Rows.Add(1, 0, "a");
        table.Rows.Add(2, 1, "b");
        table.Rows.Add(3, 1, "c");
        table.Rows.Add(4, 3, "d");
        table.Rows.Add(5, 3, "e");

如何使用LINQ进行这些操作?

How can I do these using LINQ?

a.返回DataRows,其第1列中的值也出现在column2中.

a. Return the DataRows whose values in column1 also appears in column2.

到目前为止,我做到了:

So far, I did this:

var x = (from t1 in table.AsEnumerable()
         select t1.Field<int>(0)).Intersect
        ((from t2 in table.AsEnumerable()
         select t2.Field<int>(1)).Distinct());

Bu的问题是,仅返回column1的值,而我使用的是foreach.可能是因为select t1.Field<int>(0)部分,但是我不知道如何返回DataRows本身.

Bu the problem is, only the values of column1 is returned, which I use a foreach on. Probably because of the select t1.Field<int>(0) part, but I don't know how to return the DataRows itself.

b.返回column3的值,其column1中的值也出现在column2中.

b. Return the values of column3 whose values in column1 also appears in column2.

与[a]几乎相同的问题.因为我已经使用过column1行,所以我只能返回它.我不知道如何返回DataRows和除column1以外的其他列(例如column3).

Almost the same question as [a]. I can only return the column1 row since I already used it. I don't know how to return the DataRows and other columns (e.g. column3) except column1.

我也尝试过:

var x1 = from t in table.AsEnumerable()
         select t;
var x2 = (from t in table.AsEnumerable()
          select t.Field<int>(1)).Distinct();

我希望在x1和x2上使用Intersect(),但我不知道如何.特别是因为x1有点像DataRow [],而x2有点像int [].

I was hoping to use Intersect() on x1 and x2, but I don't know how. Especially since x1 is kind of like a DataRow[] and x2 like an int[].

c.将[a]中的答案用于另一个查询.

c. Using the answer in [a] for another query.

或将LINQ中的内容用于另一个LINQ.我完全不知道如何做这样的事情.

Or using something from a LINQ for another LINQ. i have no idea at all how to do something like this.

推荐答案

一种方法:

a)    var result = (from t1 in table.AsEnumerable() 
                   join t2 in table.AsEnumerable() on t1.Field<int>(0) equals t2.Field<int>(1)  select t1).Distinct();

上面的查询返回IEnumerable<DataRow>.从此结果中,您可以选择column3的值,例如b)场景的t2.Field<int>(2).

The query above returnsIEnumerable<DataRow>.From this result you can select values of column3 like t2.Field<int>(2) for b) scenario.

这篇关于使用LINQ查询数据表的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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