2013-12-23 81 views
2

你能幫我編寫一個計算LINQ的字符串嗎?喜歡這個?每個符號重複多少次

String text="aaabbcccdde"; 
Dictionary<int,char> result=....//LINQ 
foreach (var t in result) 
{ 
    Console.WriteLine("Symbol {0} is met {1} times",t.symbol,t.times); 
} 

回答

6

你可以使用一個小的Linq:

var result = text.GroupBy(c => c) 
       .Select(g => new { symbol = g.Key, times = g.Count() }); 
foreach (var t in result) 
{ 
    Console.WriteLine("Symbol {0} is met {1} times",t.symbol,t.times); 
} 

或者更簡單地說

var result = text.GroupBy(c => c, (c, g) => new { symbol = c, times = g.Count() }); 
foreach (var t in result) 
{ 
    Console.WriteLine("Symbol {0} is met {1} times",t.symbol,t.times); 
} 
3
String text = "aaabbcccdde"; 
foreach (var t in text.GroupBy(c => c)) 
{ 
    Console.WriteLine("Symbol {0} is met {1} times", t.Key, t.Count()); 
} 

哪裏Key是被分組和Count()是次數炭出現Key