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

Gani_tpt 1,506 Reputation points
2021-04-11T12:11:36.59+00:00

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#?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,216 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ken Tucker 5,846 Reputation points
    2021-04-11T13:16:23.373+00:00

    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 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2021-04-11T14:01:59.133+00:00

    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());
    
    0 comments No comments