本文介绍了ToLookup有多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,要求多个密钥由LINQ提供的 .ToLookup 功能?我承认,这似乎不直观起初,我很期待,有没有实际的方式来做到这一点,但我希望有人知道的方式。

基本上,我希望能够通过两个值来查找,例如字符串 INT ,和检索与这两个值的对象。

示例

 公共类MyClass的{
      公共字符串StringProp {获取;集;}
      公众诠释IntProp {获取;集;}
      公共对象MOREDATA {获取;集;}
    }
    公共类主要{
      公共无效的主要(){
        HashSet的< MyClass的>设置=新的HashSet< MyClass的>();
        set.Add(新MyClass的{StringProp =一个,IntProp = 1,MOREDATA =空});
        set.Add(新MyClass的{StringProp =c的,IntProp = 4,MOREDATA =新对象()});
        set.Add(新MyClass的{StringProp =一个,IntProp = 2,MOREDATA =upupdowndown});
        set.Add(新MyClass的{StringProp =C,IntProp = 1,= MOREDATA的String.Empty});
        set.Add(新MyClass的{StringProp =C,IntProp = 4,MOREDATA =的String.Empty});
        //使用'变种',因为我不知道如何做到这一点定义。
        //我认识到,这将不会编译 - 而这就是我想要做的。
        VAR查找= set.ToLookup(X => x.StringProp和放大器;&安培; x.IntProp)
        MyClass的C =查找[一个,1]。首先(); //如果返回的第一个元素
        IEnumerable的< MyClass的>名单=查找[C,4]。 //应该返回第二个和最后一个元素
      }
    }
 

解决方案

我会使用元组 S表示这样的事情:

  VAR查找= set.ToLookup(X => Tuple.Create(x.StringProp,x.IntProp));
。MyClass的C =查找[Tuple.Create(一,1)]首先();
IEnumerable的< MyClass的>名单=查找[Tuple.Create(C,4)];
 

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 that there's no actual way to do this but I'm hoping that someone knows a way.

I basically want to be able to lookup by two values, for example a string and an int, and retrieve the object with those two values.

Example

    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
      }
    }
解决方案

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)];

这篇关于ToLookup有多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:25