如何在多个条件下使用动态LINQ连接扩展方法

时间:2015-07-30 05:54:31

标签: c# linq join dynamic-linq multiple-conditions

我正在尝试测试定义为here的动态连接扩展方法,以在多个条件下连接两个数据集(dataset1和dataset2)。我的加入条件如下所示

    outerSelector = "new ( dataset1.ToBeReconciled as col1, dataset1.TransactionDate as col2)";
innerSelector = "new ( dataset2.ToBeReconciled as col1, dataset2.TransactionDate as col2)";

这不会导致任何错误,但同时总是返回零记录,即使我有符合此条件的记录。

知道如何使这项工作?谢谢!

1 个答案:

答案 0 :(得分:0)

也许你应该从一个简单的例子开始,然后尝试解决你在那里所拥有的......我在下面写了一个简单易懂的例子。

void Main()
{
    var fruits = new List<Fruit>
    {
        new Fruit{ GroceryId = 1,Name = "Apple", ProductId = 1},
        new Fruit{ GroceryId = 1,Name = "Orange", ProductId = 2},
    };

    var groceries = new List<Grocery>
    {
        new Grocery { GroceryId = 1, Name = "Fruits and Vegetables" },
        new Grocery { GroceryId = 2, Name = "Drinks and snacks" },
    };

    var joinedResults = fruits.Join(groceries, // References the groceries declared above,
                                    fruit => fruit.GroceryId,  // Join by GroceryId located on the Fruit
                                    grocery => grocery.GroceryId,  // Join by the GroceryID located on Grocery 
                                    (product, grocery) => new 
                                    {
                                        ProductId = product.ProductId, 
                                        ProductName = product.Name, 
                                        GroceryName = grocery.Name
                                    });
}
public class Fruit
{
    public int ProductId { get; set; }
    public int GroceryId { get; set; }
    public string Name { get; set; }
}

public class Grocery
{
    public int GroceryId { get; set; }
    public string Name { get; set; }
}

Result