将Join LINQ语句缩放到多个表

时间:2016-05-02 03:12:22

标签: c# linq join

我已经提出了一些LINQ代码来连接多个表和多个字段"动态",这意味着用户选择了他想要加入的表和字段。但是我很难将这个问题搞砸到多个牌桌上而不像我在这里做的那样:

if (Tables.Count == 2)
{
    result = from dataRows1 in Tables[0].AsEnumerable()
             join dataRows2 in Tables[1].AsEnumerable() 
             on new ComparableObject(new List<DataRow> { dataRows1 },KeyFieldToJoinOn[0].Item1) 
             equals new ComparableObject(dataRows2, KeyFieldToJoinOn[0].Item2)
             select dtResult.LoadDataRow(
                 dataRows1.ItemArray.Concat(dataRows2.ItemArray)
                 .ToArray(), false);
}
else if (Tables.Count == 3)
{
    result = from dataRows1 in Tables[0].AsEnumerable()
             join dataRows2 in Tables[1].AsEnumerable() 
             on new ComparableObject(new List<DataRow> { dataRows1 }, KeyFieldToJoinOn[0].Item1) 
             equals new ComparableObject(dataRows2, KeyFieldToJoinOn[0].Item2)
             join dataRows3 in Tables[2].AsEnumerable() 
             on new ComparableObject( new List<DataRow> { dataRows1, dataRows2 },KeyFieldToJoinOn[1].Item1) 
             equals new ComparableObject(dataRows3, KeyFieldToJoinOn[1].Item2)
             select dtResult.LoadDataRow(
                 dataRows1.ItemArray.Concat(dataRows2.ItemArray)
                 .Concat(dataRows3.ItemArray)
                 .ToArray(),false);
}

我看过动态LINQ库,但我还没有看到有关如何动态加入的全面文档。所有这一切都来自于我可以在数据表上进行SQL查询,因为我可以提高查询量。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

在我看来,你应该使用foreach循环遍历表而不是写if else条件。您还可以使用LINQ根据您的要求过滤表格内容。