C# 使用count打印字符串中的不同字符
输出为system.linq.Enumable+C# 使用count打印字符串中的不同字符,c#,linq,C#,Linq,输出为system.linq.Enumable+ 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()
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();
}
}
或者使用lambda语法
Console.WriteLine(String.Join(" ", x.Select(y=>y.Key + " " + y.Count)));
或者使用lambda语法
Console.WriteLine(String.Join(" ", x.Select(y=>y.Key + " " + y.Count)));
您也可以像这样使用聚合函数:
string s = "Stack Overflows";
Console.WriteLine(String.Join(" ", s.GroupBy(c => c)
.Select(g => g.Key + " " + g.Count())));
函数可以用于任何类型(不仅仅是字符串)您也可以像这样使用聚合函数:
string s = "Stack Overflows";
Console.WriteLine(String.Join(" ", s.GroupBy(c => c)
.Select(g => g.Key + " " + g.Count())));
函数可以用于任何类型(不仅仅是字符串)请尝试此代码而不是您的代码,我已经修改了@L.B代码
Console.WriteLine(x.Select(y => String.Format("{0} {1}", y.Key, y.Count)).Aggregate((y, z) => y + String.Format(" {0}", z)));
请尝试此代码而不是您的代码,我已修改@L.B代码
Console.WriteLine(x.Select(y => String.Format("{0} {1}", y.Key, y.Count)).Aggregate((y, z) => y + String.Format(" {0}", z)));
我在你的字符串中没有看到任何
g
和p
。只有一个a
。还有两个s
。我刚刚给出了一个例子,我想要输出像s2 t1 a1c1k1o2v1e1。。。。。。。诸如此类,我在你的字符串中没有看到任何g
和p
。只有一个a
。还有两个s
。我刚刚给出了一个例子,我想要输出像s2 t1 a1c1k1o2v1e1。。。。。。。诸如此类this@user3201772那么你可能想读这个@L.B,我已经修改了你的代码,请看我的答案。Thanks@user3201772那么你可能想读这个@L.B,我已经修改了你的代码,请看我的答案。谢谢