日期:2014-05-18 浏览次数:21130 次
string tempStr = File.ReadAllText(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312"));//读取tx string pattern = @"\d"; var temp_list=Regex.Matches(tempStr,pattern).Cast<Match>().GroupBy(a=>a.Value).Select(a=>new {count=a.Count(),text=a.Key}).OrderByDescending(a=>a.count).ThenByDescending(a=>a.text).ToList(); /* + [0] { count = 12, text = "0" } <Anonymous Type> + [1] { count = 10, text = "2" } <Anonymous Type> + [2] { count = 8, text = "1" } <Anonymous Type> + [3] { count = 7, text = "7" } <Anonymous Type> + [4] { count = 6, text = "9" } <Anonymous Type> + [5] { count = 6, text = "8" } <Anonymous Type> + [6] { count = 6, text = "6" } <Anonymous Type> + [7] { count = 6, text = "3" } <Anonymous Type> + [8] { count = 5, text = "4" } <Anonymous Type> + [9] { count = 4, text = "5" } <Anonymous Type> */
------解决方案--------------------
使用Linq可以很方便的对字符串进行这样的统计,比如下面的代码:
string str = "8043283672469056709847421622639010367832281012053917805921902110075074";
var q = from c in str.ToArray<char>() orderby c group c by c into cs
select new
{
Str = cs.Key,
Count = cs.Count()
};