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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With