question

GaniTPT avatar image
0 Votes"
GaniTPT asked GaniTPT commented

How to find the duplication from the list using either LINQ or Loop in C#

I have the list. i want to return true if any duplicates found.

for example, below is the list

List<string> Listvalues = new List<string> {"E-10-XN-PP" , E-10-XN-MM, E-10-XN-MM}; ==> Found duplicates

List<string> Listvalues = new List<string> {"E-10-XN-PP" , E-10-XN-MM, E-10-XN-NM}; ==> No duplicates found

How to check the duplicates or no duplicates using LINQ or Loop in C#?

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

vb2ae avatar image
1 Vote"
vb2ae answered GaniTPT commented

You can try something like this to see if a list of string has duplicates


     public static  bool ListHasDuplicates(List<string> lst)
     {
         bool result = false;
         var distinctList = lst.Distinct().ToList();
         result = (lst.Count() == distinctList.Count());
         return !result;
     }
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Simple and excellent...it's working...

0 Votes 0 ·
karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon edited

Hello,

The following uses C#9 new expressions e.g. List<string> listValues = new () rather than List<string> listValues = new List<string>()

The following uses a language extension.

 public static class Extensions
 {
     public static bool HasDuplications(this List<string> sender) => 
         sender.GroupBy(value => value).Any(@group => @group.Count() > 1);
     public static string ToYesNoString(this bool value) => value ? "Yes" : "No";
 }

First we get yes then no.

 List<string> listValues = new ()
 {
     "E-10-XN-PP", 
     "E - 10 - XN - MM", 
     "E - 10 - XN - MM"
 };
    
 Debug.WriteLine(listValues.HasDuplications().ToYesNoString());
    
 listValues.RemoveAt(1);
    
 Debug.WriteLine(listValues.HasDuplications().ToYesNoString());




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.