gpt4 book ai didi

c# - 检查集合中的重复项

转载 作者:太空狗 更新时间:2023-10-30 00:09:36 25 4
gpt4 key购买 nike

假设您有一组 Foo 类:

class Foo
{
public string Bar;
public string Baz;
}

List<Foo> foolist;

并且您想检查此集合以查看另一个条目是否具有匹配的 Bar

bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}

Contains() 不起作用,因为它将类作为一个整体进行比较。

有没有人有更好的方法来执行此操作并适用于 .NET 2.0?

最佳答案

fooList.Exists(item => item.Bar == SomeBar)

这不是 LINQ,而是 Lambda 表达式,但尽管如此,它使用了 v3.5 功能。没问题:

fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});

这应该适用于 2.0。

关于c# - 检查集合中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/134644/

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