我的数组充满了颜色,必须找到在数组中只出现一次的颜色。
string[] colors = {"red","green","white","green","red","red"}
string[] noDupcolors = szinek.Distinct().ToArray(); //the same array without duplicates
int num = 0;
int once = 0;
for (int i = 0; i < noDupcolors.Length; i++)
{
for (int j = 0; j < S; j++)
{
if (noDupcolors[i]==colors[j])
{
num++;
}
if (num == 1)
{
once = j;
}
else
{
nums = 0;
}
}
}
Console.WriteLine(colors[once]);
我已经尝试过这个,但由于某种原因它写出绿色。 有人可以帮忙吗?谢谢。
最佳答案
您可以使用 LINQ
var result = colors.GroupBy(x => x)
.Single(x => x.Count() == 1)
.Key;
实例:https://dotnetfiddle.net/lBmR7R
请注意,如果数组中有零个或多个单一出现颜色,这将引发异常,您可以使用诸如 First
、FirstOrDefault
或 SingleOrDefault
代替Single
关于C# 查找数组中只出现一次的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70739138/