问题描述
rt....code=C#]string[]strArray=newstring[10]{"a","a","d","e","b","c","b","c","c","a"};[/code]预期结果:a,共有3个;b,共有2个;c,共有4个;d,共有1个;e,共有1个;
解决方案
解决方案二:
string[]strArray=newstring[10]{"a","a","d","e","b","c","b","c","c","a"}
解决方案三:
用key/value
解决方案四:
解决方案五:
使用Dictionary<Key,Value>可以完成楼主的需求,以下是测试代码,参考一下。usingSystem;usingSystem.Collections.Generic;namespaceTest{classProgram{staticvoidMain(string[]args){string[]strArray=newstring[10]{"a","a","d","e","b","c","b","c","c","a"};Dictionary<string,int>dict=newDictionary<string,int>();dict.Add(strArray[0],1);for(inti=1;i<strArray.Length;i++){if(dict.ContainsKey(strArray[i])){dict[strArray[i]]++;}else{dict.Add(strArray[i],1);}}//outputforeach(KeyValuePair<string,int>keyvalueindict){Console.WriteLine("{0}:{1}个",keyvalue.Key,keyvalue.Value);}Console.Read();}}}
解决方案六:
voidMain(){string[]strArray=newstring[10]{"a","a","d","e","b","c","b","c","c","a"};strArray.GroupBy(s=>s).OrderBy(t=>t.Key).Select(t=>new{t.Key,count=t.Count()}).ToList().ForEach(t=>Console.WriteLine("{0},共有{1}个.",t.Key,t.count));/*a,共有3个.b,共有2个.c,共有3个.d,共有1个.e,共有1个.*/}