Home > front end >  c# find duplicates in list of string where the case doesn't match
c# find duplicates in list of string where the case doesn't match

Time:11-02

I have a List of string (List<string>) and I want to only get the duplicates where the cases of the strings don't match. The current query gives all the duplicates.

In the below example, I only want "Chassis" because only for that, there is a "chassis" and the cases are different. Please help.

 private void btnSearchAndFlag_Click(object sender, RoutedEventArgs e)
 {
     List<string> stList = new List<string>() { 
       "Chassis", "chassis", "ABC", "ABC", "Chassis"  };
       
     var duplicates = stList
       .GroupBy(x => x, StringComparer.Ordinal)
       .Where(g => g.Count() > 1)
       .Select(y => y.Key)
       .ToList();
 }

CodePudding user response:

You can try a small modification of your initial query:

  List<string> stList = new List<string>() { 
    "Chassis", "chassis", "ABC", "ABC", "Chassis" };
 
  var duplicates = stList
    .GroupBy(item => item, StringComparer.OrdinalIgnoreCase)
    .Where(group => group.Distinct(StringComparer.Ordinal).Count() > 1)
    .Select(group => group.Key)
    .ToList();
  • Related