I have an array of strings, f.e.
string [] letters = { "a", "a", "b", "c" };
I need to find a way to determine if any string in the array appears more than once.
I thought the best way is to make a new string-array without the string in question and to use Contains,
foreach (string letter in letters)
{
string [] otherLetters = //?
if (otherLetters.Contains(letter))
{
//etc.
}
}
but I cannot figure out how.
If anyone has a solution for this or a better approach, please answer.
The easiest way is to use
GroupBy:This will first group your array using the letters as keys. It then returns only those groups with multiple entries and returns the key of these groups. As a result, you will have an
IEnumerable<string>containing all letters that occur more than once in the original array. In your sample, this is only “a”.Beware: Because LINQ is implemented using deferred execution, enumerating
lettersWithMultipleOccurencesmultiple times, will perform the grouping and filtering multiple times. To avoid this, callToList()on the result:lettersWithMultipleOccurenceswill now be of typeList<string>.