17

有没有办法要求.ToLookupLINQ 提供的功能需要多个键?

我承认一开始这似乎不直观,我希望没有实际的方法可以做到这一点,但我希望有人知道一种方法。

我基本上希望能够通过两个值进行查找,例如 astring和 an int,并使用这两个值检索对象。

例子

    public class MyClass {
      public string StringProp {get;set;}
      public int IntProp {get;set;}
      public object MoreData {get;set;}
    }

    public class Main {
      public void Main() {
        HashSet<MyClass> set = new HashSet<MyClass>();
        set.Add(new MyClass {StringProp = "a", IntProp = 1, MoreData = null});
        set.Add(new MyClass {StringProp = "c", IntProp = 4, MoreData = new object()});
        set.Add(new MyClass {StringProp = "a", IntProp = 2, MoreData = "upupdowndown"});
        set.Add(new MyClass {StringProp = "c", IntProp = 1, MoreData = string.Empty});
        set.Add(new MyClass {StringProp = "c", IntProp = 4, MoreData = string.Empty});
        // Using 'var' because I don't know how this would be defined.
        // I recognize that this will not compile - but this is what I'm trying to do.
        var lookup = set.ToLookup(x => x.StringProp && x.IntProp)
        MyClass c = lookup["a", 1].First(); // Should return the first element
        IEnumerable<MyClass> list = lookup["c", 4]; // Should return the 2nd and last elements
      }
    }
4

3 回答 3

24

我会用Tuples 来做这种事情:

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)];
于 2012-05-29T17:03:59.343 回答
7

因此,其他答案与我的想法一致,但是每次您想从查找中获取值时创建一个元组或匿名类有点麻烦。如果您可以将字符串和 int 粘贴到索引器中以获取值,那不是很好吗?通过创建自己的类来使用索引器包装查找,您可以做到这一点。

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
}

这是一个使用它的例子:

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];
于 2012-05-29T17:23:11.610 回答
6

虽然不是你真正想要的,但会做得很好:

var r = set.ToLookup(x => new { x.StringProp, x.IntProp });
var f = r[ new { StringProp = "a", IntProp = 1 } ].First();
于 2012-05-29T16:57:06.020 回答