从文本框中输入的字符串中读取所有字符,不重复和计算每个字符

我想从文本框中输入的字符串中读取所有字符,而不重复每个字符的计数,然后使用C#,Asp.Net将这些值存储到两个网格列中

例如: My name is Joe

人物出现
 M 2
是1
 n 1
 1
 e 2
我1
 s 1
 j 1
 o 1
总计11

然后将这些存储到网格视图列

您可以使用LINQ运算符GroupBy:

 string str = ":My name is Joe"; var result = str.Where(c => char.IsLetter(c)). GroupBy(c => char.ToLower(c)). Select(gr => new { Character = gr.Key, Count = gr.Count()}). ToList(); 

这将为您提供一个字段为CharacterCount的对象列表。

编辑:我添加了一个Where子句来过滤掉非字母字符。 还添加了不区分大小写的内容

现在,您必须使用result列表作为网格的绑定源。 我对ASP.NET绑定过程的理解有点生疏。 您可能需要使用CharacterCount属性而不是匿名对象创建某些类的对象(您无法绑定到字段)

 string input = "My name is Joe"; var result = from c in input.ToCharArray() where !Char.IsWhiteSpace(c) group c by Char.ToLower(c) into g select new Tuple(g.Key.ToString(),g.Count()); int total = result.Select(o => o.Item2).Aggregate((i, j) => i + j); List> tuples = result.ToList(); tuples.Add(new Tuple("Total", total)); 

并且您可以将tuples列表数据绑定到DataGrid 🙂

如果您不喜欢LINQ解决方案,可以使用foreach-loops完成以下操作:

 string str = ":My name is Joe"; var letterDictionary = new Dictionary(); foreach (char c in str) { // Filtering non-letter characters if (!char.IsLetter(c)) continue; // We use lowercase letter as a comparison key // so "M" and "m" are considered the same characters char key = char.ToLower(c); // Now we try to get the number of times we met // this key already. // TryGetValue method will only affect charCount variable // if there is already a dictionary entry with this key, // otherwise its value will be set to default (zero) int charCount; letterDictionary.TryGetValue(key, out charCount); // Either way, we now have to increment the charCount value // for our character and put it into dictionary letterDictionary[key] = charCount + 1; } foreach (var kvp in letterDictionary) { Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value); } 

最后一个周期的输出将是:

 m: 2 y: 1 n: 1 a: 1 e: 2 i: 1 s: 1 j: 1 o: 1 

现在,您必须使用其他答案中的一些技术将结果转换为可绑定到datagrid的值列表。

我已经尝试过简单的控制台应用程序..希望这会对你有所帮助..你可以在C#求解算法上查看这个

在此处输入图像描述

结果如下:

在此处输入图像描述