如何检查数组中是否有多个相同的值

时间:2015-07-03 16:06:55

标签: c#

假设我有一个具有以下值的数组

A B A A B C

如何运行一个代码,该代码将根据数组中出现的次数增加整数变量a,b和c

2 个答案:

答案 0 :(得分:7)

您可以使用GroupBy

var array = new string[] {"A", "B", "A", "A", "B", "C" };

var counts = array
    .GroupBy(letter => letter)
    .Select(g => new { Letter = g.Key, Count = g.Count() });

如果您想单独获取计数,可以将所有内容放入字典中

var countsDictionary = array
    .GroupBy(letter => letter)
    .ToDictionary(g => g.Key, g => g.Count());

var aCount = countsDictionary["A"];
var bCount = countsDictionary["B"];
//etc...

答案 1 :(得分:0)

查看https://msdn.microsoft.com/en-us/library/vstudio/bb535181%28v=vs.100%29.aspx

底部的示例

它基本上可以满足您的需求。

var array = new string[] {"A", "B", "A", "A", "B", "C" };
int a = array.Count(p => p == "A");