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


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);

LINQ: Find Duplicates (advanced example with objects), Select will return distinct values of Key property. 20. // SelectMany will return all duplicates objects. 21. 22. var duplicates = list.GroupBy(s => s.Id). 23 .Where(g  LINQ: Find Duplicates (advanced example with objects) | Test your C# code online with .NET Fiddle code editor.

Dim itemsGroupedByID = lstOutcomes.GroupBy(Function(x) x.ID)
Dim duplicateItems = itemsGroupedByID.Where(Function(x) x.Count > 1) _
                                     .SelectMany(Function(x) x) _

If duplicateItems.Count > 0
    valid = False
    Dim errorMessage = "The following items have a duplicate ID: " & _
                       String.Join(", ", duplicateItems.Select(Function(x) x.Name))
End If

LINQ Find String Duplicates in List, Count() > 1) discards all the "sub lists" which have only one object, which means they didn't repeat values; Select(y => y.$$anonymous$$ey) will  Remove Duplicates From Dropdownlist With LINQ? How To Check ListView For Duplicates; Check Array For Duplicates Using A Do Until Loop? Check Internal And External Duplicates? GRFinger X SDK - Run Through The Database To Check For Duplicates ? Saving Txt File Check For Duplicates? Compare Two Objects To Check If All The Properites Of Both The Objects Have Same Value Or Not? Remove Duplicates From A List(Of T)? Marking Duplicates In A List While Not Sorting

I'll take back what Saeed Amiri said in C# and complete it.

        Dim valid As Boolean = true
    dim duplicatedItems = lst.Skip(1) _
        .Where(Function(x,index) x.ID = lst(index).ID)

    Dim count As Integer = duplicatedItems.Count()
    For Each item As objectType In duplicatedItems
        valid = False
        Console.WriteLine("id: " & item.ID & "Name: " & item.Name)

[Solved] How do I get duplicate values from two lists?, Not clear if your question is asking to find duplicate in a list or in .net - how to get duplicate items from a list in - Stack Overflow[^] This is the linq query that I came up with after doing quick research test.Count != test.Select(c => new { c.checkThat, c.checkThis }).Distinct().Count() I am not certain if this is definitely better than this answer var duplicates = test.GroupBy(x => new {x.checkThis, x.checkThat}) .Where(x => x.Skip(1).Any());

The project is behind, I just hacked it together like this:

    ' For each outcome, if it is in the list of valid outcomes more than once, and it is not in the list of 
    ' duplicates, add it to the duplicates list.
    Dim lstDuplicates As New List(Of objectType)
    For Each outcome As objectType In lstOutcomes
        'declare a stable outcome variable
        Dim loutcome As objectType = outcome
        If lstOutcomes.Where(Function(o) o.ID = loutcome.ID).Count > 1 _
        AndAlso Not lstDuplicates.Where(Function(d) d.ID = loutcome.ID).Count > 0 Then
        End If
    If lstDuplicates.Count > 0 Then
        valid = False
        sbErrors.Append("There cannot be multiple outcomes of any kind. The following " & lstDuplicates.Count & _
                        " outcomes are duplicates: ")
        For Each dup As objectType In lstDuplicates
            sbErrors.Append("""" & dup.Name & """" & " ")
        sbErrors.Append("." & vbNewLine)
    End If

VB.NET Remove all duplicate values from List(of t) LINQ, VB.NET Remove all duplicate values from List(of t) LINQ RRS feed DoEvents() have no idea what it does and those who know what it does never use it." LINQ is for selecting so you'll need to first get the items to remove  var hash = new HashSet<int>(); var duplicates = list.Where(i => !hash.Add(i)); will lead to a list that includes all occurrences of duplicates. So if you have four occurrences of 2 in your list, then your duplicate list will contain three occurrences of 2, since only one of the 2's can be added to the HashSet.

It is late, but though it could help others.

You can achieve this with a pair of very clean one-liners:

Dim lstOutcomes As IList(Of T)

Dim FoundDuplicates As Boolean
FoundDuplicates = lstOutcomes.Any(Function(p) lstOutcomes.ToArray.Count(Function(q) p.ID = q.ID and p.Name=q.Name) > 1)

Dim ListOfDuplicates As IList(Of T)
ListOfDuplicates = lstOutcomes.Where(Function(p) lstOutcomes.ToArray.Count(Function(q) p.ID = q.ID And p.Name = q.Name) > 1)

Then you can clean the list of duplicates so that it contains the duplicate only once:

Dim CleanList as IList(of T)
For Each MyDuplicate As T in ListOfDuplicates
    If not CleanList.Any(function(p) p.ID = MyDuplicate.ID And p.Name = MyDuplicate.Name) then
    End If

Or as a one-liner, although it does not read as nicely

ListOfDuplicates.ForEach(sub(p) If not CleanList.Any(function(q) p.ID = q.ID And p.Name = q.Name) then CleanList.Add(p))

Finally, as an anticipation of future requirements, you should define "what a duplicate is" as a separate thing. A delegate is quite convenient for this:

Dim AreDuplicates as Func(of T, T, Boolean) = Function(a,b) a.ID = b.ID And a.Name = b.Name
FoundDuplicates = lstOutcomes.Any(Function(p) lstOutcomes.ToArray.Count(Function(q) AreDuplicates(p,q) ) > 1)

Enumerable.Distinct Method (System.Linq), List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, If you want to return distinct elements from sequences of objects of some custom data type, you bool Equals(Product other) { //Check whether the compared object is null. if (​Object. method directly or by using foreach in Visual C# or For Each in Visual Basic. LINQ equivalent of foreach for IEnumerable<T> Best way to repeat a character in C# ; Type Checking: typeof, GetType, or is? LINQ: How to perform.Max() on a property of all objects in a collection and return the object with maximum value

C# Remove Duplicates From List, Eliminate duplicate elements from a List with Distinct, HashSet, or for-loops in an optimal way. We want to find all objects with just a unique field (like the Key field). Tip: We can Linq; class Item { public int Key; public string Value; } class  But with ToList we convert it easily back into a List. IEnumerable. VB.NET program that filters duplicates Module Module1 Sub Main () ' Create list and add values. Dim values As List (Of Integer) = New List (Of Integer) values.Add (1) values.Add (2) values.Add (2) values.Add (3) values.Add (3) values.Add (3) ' Filter distinct elements, and convert back into list.

Find duplicates in a List in C#, Linq;. public class Example. {. public static void Main(). {. List<int> list = new List<​int>() {3, 5, 3, 2, 7, 7, 5, 6};. IEnumerable<int> duplicates = list.GroupBy(x => x). In Visual Basic, you identify the SQL Server database objects, such as tables, views, and stored procedures, that you want to access by using a LINQ to SQL file. A LINQ to SQL file has an extension of .dbml.

Remove duplicates from a List in C#, Use the Distinct() method to remove duplicates from a list in C#.Firstly Linq; public class Demo { public static void Main() { List<int> arr1 = new  The code above uses the LINQ GroupBy function to group the list by Make and Model and then use the LINQ Select function to get the first result of the grouped data. The figure below produced the result. Output. Option 2: Using a combination of LINQ Select and Distinct operators: