如何使用LINQ执行动态联接 [英] How to perform Dynamic Join using LINQ

查看:78
本文介绍了如何使用LINQ执行动态联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏.每个集合都包含特定类型的实例.我需要使用每个集合中实例的属性之一来加入这两个集合.问题是,我将只在运行时才知道要用于连接的属性.那么,如何编写用于动态Join的LINQ查询?这是带有静态连接的LINQ查询的代码.在下面的示例代码中,您将注意到我正在使用MyTran.MyAmountUSD = YourTran.YourAmountUSD加入两个集合.但是在实际情况下,我将知道仅在运行时将哪个属性用于连接.因此,有时我可能需要加入MyTran.MyAmountGBP = YourTran.YourAmountGBP.

I have two collections. Each collection contains instances of a specific type. I need to join these two collections using one of the properties of the instances from each of the collections. The issue is that I will come to know which property to use for join only during run time. So how do I write the LINQ query for a dynamic Join? Here is the code with LINQ query with static join. In the following sample code you will notice that I am joining two collections using MyTran.MyAmountUSD = YourTran.YourAmountUSD. But in real scenario, I will come to know which property to use for join only during run time. So sometime I might be required to join on MyTran.MyAmountGBP = YourTran.YourAmountGBP.

class MyTran
{
    public int Id { get; set; }
    public double MyAmountUSD { get; set; }
    public double MyAmountGBP { get; set; }
}

class YourTran
{
    public int Id { get; set; }
    public double YourAmountUSD { get; set; }
    public double YourAmountGBP { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<MyTran> fMyTranList = new List<MyTran>();
        List<YourTran> fYourTranList = new List<YourTran>();

        fMyTranList.Add(new MyTran { Id = 1, MyAmountGBP = 100, MyAmountUSD = 1000 });
        fMyTranList.Add(new MyTran { Id = 2, MyAmountGBP = 101, MyAmountUSD = 2000 });

        fYourTranList.Add(new YourTran { Id = 11, YourAmountGBP=100, YourAmountUSD=1000 });
        fYourTranList.Add(new YourTran { Id = 12, YourAmountGBP = 102, YourAmountUSD = 3000 });

        var query = from fMyTrans in fMyTranList
                    join fYourTrans in fYourTranList
                         on fMyTrans.MyAmountUSD equals fYourTrans.YourAmountUSD
                    select new
                    {
                        MyId = fMyTrans.Id,
                        YourId = fYourTrans.Id,
                        MyAmtUSD = fMyTrans.MyAmountUSD,
                        MyAmtGBP = fMyTrans.MyAmountGBP,
                        YourAmtUSD = fYourTrans.YourAmountUSD,
                        YourAmtGBP = fYourTrans.YourAmountGBP
                    };

        foreach (var fMatch in query)
        {
            Console.WriteLine(fMatch);
        }
    }
}

推荐答案

解决此问题的第一个线索是使用

The first clue to solving this is to re-write your join using lamda syntax for the Join

var query = fMyTranList.Join(fYourTranList,
               a => a.MyAmountGBP, 
               b => b.YourAmountGBP, 
               (c,d) => new
                    {
                        MyId = c.Id,
                        YourId = d.Id,
                        MyAmtUSD = c.MyAmountUSD,
                        MyAmtGBP = c.MyAmountGBP,
                        YourAmtUSD = d.YourAmountUSD,
                        YourAmtGBP = d.YourAmountGBP
                    });

实时: http://rextester.com/OGC85986

应明确指出,要使其动态化,就需要传递给您的通用"联接函数3个函数

Which should make it clear that making this dynamic would require passing in to your "generic" join function 3 functions

  1. 用于选择LHS密钥的Func<MyTran,TKey>功能
  2. 用于选择RHS密钥的Func<YourTran,TKey>功能
  3. 用于选择结果的Func<MyTran,YourTran,TResult>函数
  1. a Func<MyTran,TKey> function for selecting the key for LHS
  2. a Func<YourTran,TKey> function for selecting the key for RHS
  3. a Func<MyTran,YourTran,TResult> function for selecting the result

因此,从那里您可以使用反射使这一切变得动态:

So from there you could use reflection to make this all a bit dynamic:

public static class DynamicJoinExtensions
{
    public static IEnumerable<dynamic> DynamicJoin(this IEnumerable<MyTran> myTran, IEnumerable<YourTran> yourTran, params Tuple<string, string>[] keys)
    {
        var outerKeySelector = CreateFunc<MyTran>(keys.Select(k => k.Item1).ToArray());
        var innerKeySelector = CreateFunc<YourTran>(keys.Select(k => k.Item2).ToArray());

        return myTran.Join(yourTran, outerKeySelector, innerKeySelector, (c, d) => new
        {
            MyId = c.Id,
            YourId = d.Id,
            MyAmtUSD = c.MyAmountUSD,
            MyAmtGBP = c.MyAmountGBP,
            YourAmtUSD = d.YourAmountUSD,
            YourAmtGBP = d.YourAmountGBP
        }, new ObjectArrayComparer());
    }

    private static Func<TObject, object[]> CreateFunc<TObject>(string[] keys)
    {
        var type = typeof(TObject);
        return delegate(TObject o)
        {
            var data = new object[keys.Length];
            for(var i = 0;i<keys.Length;i++)
            {
                var key = type.GetProperty(keys[i]);
                if(key == null)
                    throw new InvalidOperationException("Invalid key: " + keys[i]);
                data[i] = key.GetValue(o);
            }
            return data;
        };
    }

    private class ObjectArrayComparer : IEqualityComparer<object[]>
    {

        public bool Equals(object[] x, object[] y)
        {
            return x.Length == y.Length
                   && Enumerable.SequenceEqual(x, y);
        }

        public int GetHashCode(object[] o)
        {
            var result = o.Aggregate((a, b) => a.GetHashCode() ^ b.GetHashCode());
            return result.GetHashCode();
        }
    }
}

与您的示例相匹配的用法将是:

Usage to match your example would then be:

var query = fMyTranList.DynamicJoin(fYourTranList, 
               Tuple.Create("MyAmountGBP", "YourAmountGBP"));

但是由于键是params,因此您可以根据需要传递尽可能多的信息:

but as the keys are params you can pass as many as you like:

var query = fMyTranList.DynamicJoin(fYourTranList, 
              Tuple.Create("MyAmountGBP", "YourAmountGBP"), 
              Tuple.Create("AnotherMyTranProperty", "AnotherYourTranProperty"));

实时示例: http://rextester.com/AAB2452

这篇关于如何使用LINQ执行动态联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆