C# 检查集合中的重复项
假设您有一组C# 检查集合中的重复项,c#,.net,.net-2.0,C#,.net,.net 2.0,假设您有一组Foo类: class Foo { public string Bar; public string Baz; } List<Foo> foolist; Contains()不起作用,因为它将类作为一个整体进行比较 有没有人有更好的方法来实现这一点,并且适合.NET2.0?doulist.Exists(item=>item.Bar==SomeBar) 或者与匿名代表一起 存在(delegate(Foo item){return item.Bar==So
Foo
类:
class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
Contains()
不起作用,因为它将类作为一个整体进行比较
有没有人有更好的方法来实现这一点,并且适合.NET2.0?doulist.Exists(item=>item.Bar==SomeBar)
或者与匿名代表一起
存在(delegate(Foo item){return item.Bar==SomeBar;})您可能希望使用C5.HashSet,并为Foo实现Equals和GetHashCode()。实现接口,并使用匹配方法
公共类MyFooComparer:IEqualityComparer{
公共bool等于(Foo Foo 1,Foo Foo 2){
返回等于(foo1.Bar,foo2.Bar);
}
公共int GetHashCode(Foo-Foo){
返回foo.Bar.GetHashCode();
}
}
Foo exampleFoo=新的Foo();
例如foo.Bar=“someBar”;
if(myList.Contains(例如,新的MyFooComparer())){
...
}
如果需要该元素,还可以使用List.Find()并传入一个委托,该委托将为“匹配”()的定义返回true
这里有一个如何在MSDN文档上定义委托的示例。如果类的“栏”是唯一的(类Foo的键),则可以尝试实现System.Collections.ObjectModel.KeyedCollection。非常简单:只需实现GetKeyForItem()方法
class-Foo
{
公共字符串栏;
公共字符串Baz;
}
类傻瓜:KeyedCollection
{
受保护的重写字符串GetKeyForItem(Foo项)
{
返回项.Bar;
}
}
愚人主义者;
这不是LINQ,而是一个Lambda表达式,但它使用了v3.5特性。没问题:
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
这在2.0中应该可以使用。如果您在Foo上覆盖Equals以在Bar上生成key,Contains()将起作用。如果您可以使用LINQ,则可以执行以下操作:
bool contains = foolist.Where(f => f.Bar == someBar).Count() != 0;
嗯。。。您定义了IEqualityComparer,但实际上并没有使用它。
class Foo
{
public string Bar;
public string Baz;
}
class FooList : KeyedCollection<string, Foo>
{
protected override string GetKeyForItem(Foo item)
{
return item.Bar;
}
}
FooList fooList;
fooList.Exists(item => item.Bar == SomeBar)
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
bool contains = foolist.Where(f => f.Bar == someBar).Count() != 0;