gpt4 book ai didi

c# - ToLookup 与多个键

转载 作者:可可西里 更新时间:2023-11-01 07:51:20 25 4
gpt4 key购买 nike

LINQ 提供的 .ToLookup 函数有没有办法要求多个键?

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

我基本上希望能够通过两个值进行查找,例如 stringint,并检索具有这两个值的对象。

例子

    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
}
}

最佳答案

我会用 Tuple 来做这类事情:

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

关于c# - ToLookup 与多个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com