在Datset上的运行时使用C#动态Linq查询 [英] c# dynamic linq query at runtime on datset
本文介绍了在Datset上的运行时使用C#动态Linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要您的帮助来解决一个小问题.我想使以下LINQ查询动态(在运行时),因为我不知道数据库中将有多少个表(在运行时知道表名).
I need your help for a small problem. I would like to make the following LINQ query dynamic (at runtime) because I don´t know how many tables there will be in the database (the tablenames are known while runtime).
var query = from row1 in ds.Tables["tab1"].AsEnumerable()
from row2 in ds.Tables["tab2"].AsEnumerable()
from row3 in ds.Tables["tab3"].AsEnumerable()
select new { row1, row2, row3 };
在这种情况下,是否可以在生成动态LINQ查询并将结果写入数据表或数组中?
Is this possible at generate a dynamic LINQ query in this case and write the result to a datatable or array?
提前谢谢!
推荐答案
此扩展方法可以创建以下项的笛卡尔积DataSet
中的所有表行.
This extension method can create a cartesian product of all tables rows in a DataSet
.
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item })
);
}
}
现在您可以通过以下方式使用它:
Now you can use it in this way:
IEnumerable<IEnumerable<DataRow>> allTablesRows = ds.Tables.Cast<DataTable>()
.Select(table => table.AsEnumerable())
.CartesianProduct();
输出:
foreach (var x in allTablesRows)
{
foreach (DataRow row in x)
{
Console.WriteLine("table:{0} fields:{1}",
row.Table.TableName,
string.Join(",", row.ItemArray));
}
}
这篇关于在Datset上的运行时使用C#动态Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文