【发布时间】:2011-08-24 15:57:57
【问题描述】:
假设我有这个初始代码:
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 完成这些操作?
一个。返回 column1 中的值也出现在 column2 中的 DataRows。
到目前为止,我是这样做的:
var x = (from t1 in table.AsEnumerable()
select t1.Field<int>(0)).Intersect
((from t2 in table.AsEnumerable()
select t2.Field<int>(1)).Distinct());
但问题是,只返回 column1 的值,我在上面使用了foreach。可能是因为 select t1.Field<int>(0) 部分,但我不知道如何返回 DataRows 本身。
b.返回 column3 的值,其 column1 中的值也出现在 column2 中。
与[a]几乎相同的问题。我只能返回 column1 行,因为我已经使用了它。我不知道如何返回除 column1 之外的 DataRows 和其他列(例如 column3)。
我也试过这个:
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[]。
c。将 [a] 中的答案用于另一个查询。
或者将 LINQ 中的某些内容用于另一个 LINQ。我完全不知道如何做这样的事情。
【问题讨论】: