我有一个字符串数组,其中可能包含1个或多个元素,这些元素具有各种字符串值。 我需要找到数组中最常见的字符串。
string aPOS[] = new string[]{"11","11","18","18","11","11"};
我需要在这种情况下返回
"11"
。我有一个字符串数组,其中可能包含1个或多个元素,这些元素具有各种字符串值。 我需要找到数组中最常见的字符串。
string aPOS[] = new string[]{"11","11","18","18","11","11"};
"11"
。尝试使用LINQ来实现类似以下的操作。
int mode = aPOS.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
string[] aPOS = new string[] { "11", "11", "18", "18", "11", "11"};
var count = new Dictionary<string, int>();
foreach (string value in aPOS)
{
if (count.ContainsKey(value))
{
count[value]++;
}
else
{
count.Add(value, 1);
}
}
string mostCommonString = String.Empty;
int highestCount = 0;
foreach (KeyValuePair<string, int> pair in count)
{
if (pair.Value > highestCount)
{
mostCommonString = pair.Key;
highestCount = pair.Value;
}
}
var results = aPOS.GroupBy(v=>v) // group the array by value
.Select(g => new { // for each group select the value (key) and the number of items into an anonymous object
Key = g.Key,
Count = g.Count()
})
.OrderByDescending(o=>o.Count); // order the results by count
// results contains the enumerable [{Key = "11", Count = 4}, {Key="18", Count=2}]
这里是官方的Group By文档
string[] aPOS = new string[]{"11","11","18","18","11","11"};
。 - Mayank