LINQ提供的.ToLookup
函数是否需要多个键?ToLookup with multiple keys
我承认这起初看起来不直观,我期待没有实际的方法来做到这一点,但我希望有人知道一种方式。
我基本上希望能够通过两个值查找,例如string
和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
}
}
我没有看到这是如何帮助。 – DarthVader
谢谢Gabe。我将尝试一点,并让你知道它是如何工作的。 – Merwer