Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find indexes of duplicate strings in C# List [duplicate]

Tags:

arrays

c#

list

I have a List of strings:

["String1"]
["String2"]
["String1"]
["String3"]
["String2"]
["String1"]

That I need to search and find the indexes of "String1" in the List and also count how many times "String1" occurred. I've reviewed this answer but I'm new to this type of coding in C# and I'm unclear how to extract the index values, so if you could explain how to use the solution, that'd be great!

like image 802
Mark Avatar asked Dec 29 '25 17:12

Mark


1 Answers

The code from the other answer, which I will duplicate here for reference,

var duplicates = data
  .Select((t,i) => new { Index = i, Text = t })
  .GroupBy(g => g.Text)
  .Where(g => g.Count() > 1);

Returns an IEnumerable of IGrouping, which is itself an IEnumerable of an anonymous type. You can get the indexes out of the result like this:

foreach(var group in duplicates)
{
    Console.WriteLine("Duplicates of {0}:", group.Key)
    foreach(var x in group)
    {
        Console.WriteLine("- Index {0}:", x.Index)
    }
}

However, if all you want to do is get a list of indexes, you can use the SelectMany extension method:

var duplicateIndexes = data
  .Select((t,i) => new { Index = i, Text = t })
  .GroupBy(g => g.Text)
  .Where(g => g.Count() > 1)
  .SelectMany(g => g, (g, x) => x.Index);

This will return an IEnumerable of int's.

like image 115
p.s.w.g Avatar answered Jan 01 '26 08:01

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!