Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ VB how to check for duplicates in a list of objects

I have a list of objects, each with 2 relevant properties: "ID" and "Name". Lets call the list "lstOutcomes". I need to check the list for duplicates (meaning object1.ID = object2.ID, etc.) and set a flag (valid = false, or something) if there is at least one duplicate. Also, it would be nice to send a message to the user mentioning the "Name" of the object, when it fails.

I am sure I will need to use the Group By operator to do this, but I am not used to doing that in LINQ, and the examples out there are just not helping me. This article seems to be close to what i need, but not quite and it's in C#.

Here is a starting stab at it...

Dim duplist = _
    (From o As objectType In lstOutcomes _
    Group o By o.ID Into g = Group _
    Let dups = g.Where(Function(h) g.Count > 1) _
    Order By dups Descending).ToArray

if duplist.count > 0 then
valid = false
end if

help?

like image 432
Watki02 Avatar asked Oct 25 '25 14:10

Watki02


1 Answers

I'll write it in C#, but hope you could convert it to VB. It does not use join and is O(n log n), and I assumed you have List<T>:

lst.Sort();  //O(nlogn) part.

var duplicatedItems = lst.Skip(1).Where((x,index)=>x.ID == lst[index].ID);
like image 115
Saeed Amiri Avatar answered Oct 27 '25 11:10

Saeed Amiri