2014-02-28 24 views
0
class Program 
{ 
    static void Main(string[] args) 
    { 
     string s = "Stack Overflows"; 

     var x = from c in s.ToLower() 
       group c by c into a 
       select new { a.Key, Count = a.Count() }; 
     Console.WriteLine(Convert.ToString(x)); 

     Console.Read(); 
    } 
} 

输出是system.linq.Enumable +打印不同的字符数

i want output like a 2 g 1 s 1 p 2 r 1 
+2

我没有看到任何'g'和你的字符串中有'p'。而且只有一个'a'。和两个'''。 –

+0

我刚刚给了我想要的输出例如s 2 t 1 a 1 c 1 k 1 o 2 v1 e 1 .......等等这样的例子 – user3201772

回答

4
Console.WriteLine(String.Join(" ", x.Select(y=>y.Key + " " + y.Count))); 

或使用lambda语法

string s = "Stack Overflows"; 
Console.WriteLine(String.Join(" ", s.GroupBy(c => c) 
            .Select(g => g.Key + " " + g.Count()))); 
+0

谢谢@ L.B。它的工作 – user3201772

+0

@ user3201772然后你可能想阅读这个http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

+0

@LB,我修改了你的代码,请看我的回答。谢谢 –

0

您还可以使用聚合函数这样:

Console.WriteLine(x.Select(y => String.Format("{0} {1}", y.Key, y.Count)).Aggregate((y, z) => y + String.Format(" {0}", z))); 

Aggregate功能,可用于任何类型的(不仅是字符串)

0

试试这个代码,而不是你的代码,我已经修改@LB代码

string s = "Stack Overflows";  
var x = String.Join("", (from c in s.ToLower() 
     group c by c into a 
     select new { a.Key, Count = a.Count() }).Select(y => y.Key + " " + y.Count));