c# – 具有多个键的ToLookup

前端之家收集整理的这篇文章主要介绍了c# – 具有多个键的ToLookup前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法为LINQ提供的.ToLookup函数要求多个键?

我会承认,这似乎是非直观的,我希望没有实际的方法来做到这一点,但我希望有人知道一个方法.

我基本上希望能够通过两个值进行查找,例如一个字符串和一个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",MoreData = string.Empty});
        set.Add(new MyClass {StringProp = "c",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
      }
    }

解决方法

我会使用元组这种事情:
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)];
原文链接:https://www.f2er.com/csharp/96611.html

猜你在找的C#相关文章