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
答案 0 :(得分: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())));
答案 1 :(得分:0)
你也可以使用这样的聚合函数:
Console.WriteLine(x.Select(y => String.Format("{0} {1}", y.Key, y.Count)).Aggregate((y, z) => y + String.Format(" {0}", z)));
Aggregate函数可用于任何类型(不仅仅是字符串)
答案 2 :(得分:0)
尝试使用此代码而不是代码,我修改了@ L.B代码
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));