ToLookup with multiple keys

前端 未结 3 1788
囚心锁ツ
囚心锁ツ 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<T1, T2, TOut>
    {
        private ILookup<Tuple<T1, T2>, TOut> lookup;
        public MyLookup(IEnumerable<TOut> source, Func<TOut, Tuple<T1, T2>> keySelector)
        {
            lookup = source.ToLookup(keySelector);
        }
    
        public IEnumerable<TOut> 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<MyClass> data = null; //TODO populate with real data
    var lookup = new MyLookup<string, int, MyClass>(data
        , item => Tuple.Create(item.StringProp, item.IntProp));
    
    IEnumerable<MyClass> someValue = lookup["c", 4];
    
    0 讨论(0)
  • 2021-02-07 08:11

    Although not what you really want, but will do the job just fine:

    var r = set.ToLookup(x => new { x.StringProp, x.IntProp });
    var f = r[ new { StringProp = "a", IntProp = 1 } ].First();
    
    0 讨论(0)
  • 2021-02-07 08:21

    I would use Tuples for this sort of thing:

    var lookup = set.ToLookup(x => Tuple.Create(x.StringProp, x.IntProp));
    MyClass c = lookup[Tuple.Create("a", 1)].First();
    IEnumerable<MyClass> list = lookup[Tuple.Create("c", 4)];
    
    0 讨论(0)
提交回复
热议问题