-
qq_遁去的一_1
这是我可以考虑使用的一种方法Dictionary<string, int>:public static Dictionary<string, int> GetObjectCount(List<string> items){ // Dictionary object to return Dictionary<string, int> keysAndCount = new Dictionary<string, int>(); // Iterate your string values foreach(string s in items) { // Check if dictionary contains the key, if so, add to count if (keysAndCount.ContainsKey(s)) { keysAndCount[s]++; } else { // Add key to dictionary with initial count of 1 keysAndCount.Add(s, 1); } } return keysAndCount;}然后取回结果并打印到控制台:Dictionary<string, int> dic = GetObjectCount(list);//Print to Consoleforeach(string s in dic.Keys){ Console.WriteLine(s + " has a count of: " + dic[s]);}
-
犯罪嫌疑人X
我不知道你为什么要为此寻找 LINQ less 的解决方案,因为这可以很容易和有效地完成。我强烈建议您使用它并按照以下方式操作:var _group = list.GroupBy(i => i);string result = "";foreach (var grp in _group) result += grp.Key + ": " + grp.Count() + Environment.NewLine;MessageBox.Show(result);否则,如果你真的无法使用 LINQ,你可以像下面那样做:Dictionary<string, int> listCount = new Dictionary<string, int>();foreach (string item in list) if (!listCount.ContainsKey(item)) listCount.Add(item, 1); else listCount[item]++;string result2 = "";foreach (KeyValuePair<string, int> item in listCount) result2 += item.Key + ": " + item.Value + Environment.NewLine;MessageBox.Show(result2);
-
九州编程
你可以尝试这样的事情:public int countOccurances(List<string> inputList, string countFor){ // Identifiers used are: int countSoFar = 0; // Go through your list to count foreach (string listItem in inputList) { // Check your condition if (listItem == countFor) { countSoFar++; } } // Return the results return countSoFar;}这将为您提供任何刺痛的计数。一如既往,有更好的方法,但这是一个好的开始。或者如果你想要:public string countOccurances(List<string> inputList, string countFor){ // Identifiers used are: int countSoFar = 0; string result = countFor; // Go through your list to count foreach (string listItem in inputList) { // Check your condition if (listItem == countFor) { countSoFar++; } } // Return the results return countFor + " = " countSoFar;}或者更好的选择:private static void CountOccurances(List<string> inputList, string countFor) { int result = 0; foreach (string s in inputList) { if (s == countFor) { result++; } } Console.WriteLine($"There are {result} occurrances of {countFor}.");}