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