ToLookup with multiple keys

前端 未结 3 1790
囚心锁ツ
囚心锁ツ 2021-02-07 07:37

Is there a way to require multiple keys for the .ToLookup function provided by LINQ?

I will admit that this seems non-intuitive at first, and I\'m expecting

3条回答
  •  离开以前
    2021-02-07 08:03

    So the other answers are along the lines that I was thinking, but it's somewhat cumbersome to be creating a tuple or anonymous class each time you want to just get a value out of the lookup. Wouldn't it be great if you could just stick a string and an int into an indexer to get the value out. By creating your own class to wrap the lookup with an indexer you can do exactly that.

    public class MyLookup
    {
        private ILookup, TOut> lookup;
        public MyLookup(IEnumerable source, Func> keySelector)
        {
            lookup = source.ToLookup(keySelector);
        }
    
        public IEnumerable this[T1 first, T2 second]
        {
            get
            {
                return lookup[Tuple.Create(first, second)];
            }
        }
    
        //feel free to either expose the lookup directly, or add other methods to access the lookup
    }
    

    Here is an example of it being used:

    IEnumerable data = null; //TODO populate with real data
    var lookup = new MyLookup(data
        , item => Tuple.Create(item.StringProp, item.IntProp));
    
    IEnumerable someValue = lookup["c", 4];
    

提交回复
热议问题