gpt4 book ai didi

C# LINQ 比较列表值

转载 作者:行者123 更新时间:2023-11-30 13:17:41 25 4
gpt4 key购买 nike

我有两个包含两种不同自定义类型的列表。这两种类型共享 2 个共同属性。

例如:

List<foo>;
List<bar>;

它们都有属性,例如,named Name 和 Age。

我想返回一个包含所有 bar 对象的新列表,其中 bar 的 Name 和 Age 属性存在于任何 foo 对象中。执行此操作的最佳方法是什么?

谢谢

最佳答案

假设共享属性正确地实现了平等等,你可能想做这样的事情:

// In an extensions class somewhere. This should really be in the standard lib.
// We need it for the sake of type inference.
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
return new HashSet<T>(items);
}

var shared = foos.Select(foo => new { foo.SharedProperty1, foo.SharedProperty2 })
.ToHashSet();

var query = bars.Where(bar => shared.Contains(new { bar.SharedProperty1,
bar.SharedProperty2 }));

使用连接的其他选项肯定会起作用 - 但我发现这更清楚地表达了您只想查看每个 bar 条目一次的想法,即使有多个 foo 具有该属性的项目。

关于C# LINQ 比较列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6817517/

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