繁体   English   中英

使用LINQ查询数据表的另一个帮助

[英]Another help with querying a DataTable using LINQ

我有和以前一样的问题 我仍在使用相同的示例。

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

我这样做是为了返回column3的值,其column1中的值也出现在column2中:

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

如何根据上面的LINQ获取column3的值?

我可以在这里使用接受的答案:

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

虽然我认为我不能在第一个LINQ的对面使用它,但可以将其翻译为“返回column3的值,而column1 的值出现在column2中。” 但是,我可以将上面的LINQ更改为Except()而不是在Intersect() 我只需要知道如何使用var x来获取Rows的集合或column3的值。

这些应该给您您想要的:

// collection of datarows
var rows = table.AsEnumerable().Where(i => i.Field<int>(0) == i.Field<int>(1));

// collection of strings (field 3 of rows)
var rowvalues = rows.Select(j => j.Field<string>(3));

暂无
暂无

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

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