Check for duplicates in a collection

Suppose you have a collection of Foo classes:

 class Foo { public string Bar; public string Baz; } List<Foo> foolist; 

And you want to check this collection to see if another record matches Bar .

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

Contains() does not work because it compares classes as integers.

Is there anyone better way to do this that works for .NET 2.0?

+4
source share
8 answers
 fooList.Exists(item => item.Bar == SomeBar) 

This is not LINQ, but a Lambda expression, but nonetheless it uses the v3.5 function. No problems:

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

This should work in version 2.0.

+10
source

Implement the IEqualityComparer <T> interface and use the appropriate Contains method.

 public class MyFooComparer: IEqualityComparer<Foo> { public bool Equals(Foo foo1, Foo foo2) { return Equals(foo1.Bar, foo2.Bar); } public int GetHashCode(Foo foo) { return foo.Bar.GetHashCode(); } } Foo exampleFoo = new Foo(); exampleFoo.Bar = "someBar"; if(myList.Contains(exampleFoo, new MyFooComparer())) { ... } 
+4
source

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

or with an anonymous delegate

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

0
source

If you need this element, you can also use List.Find () and pass in a delegate that returns true for your definition of "match" ( http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx ).

Here is an example of how to define a delegate in this MSDN document.

0
source

If the Bar for your class is unique (the key to the Foo class), you can try to implement System.Collections.ObjectModel.KeyedCollection. It's pretty simple: just implement the GetKeyForItem () method.

 class Foo { public string Bar; public string Baz; } class FooList : KeyedCollection<string, Foo> { protected override string GetKeyForItem(Foo item) { return item.Bar; } } FooList fooList; 
0
source

If you override Equals to Foo to make the key in the panel, Contains () will work.

0
source

If you can use LINQ, you can do the following:

 bool contains = foolist.Where(f => f.Bar == someBar).Count() != 0; 
0
source

You might want to use C5.HashSet and implement Equals and GetHashCode () for Foo.

-1
source

Source: https://habr.com/ru/post/1277176/


All Articles