简体   繁体   English

LINQ C# 从字符串中选择字符

[英]LINQ C# Selecting characters from string

I have a string that I convert to a char array and then I use LINQ to select the different characters inside the char array and then order them by Descending but only catch the characters, not the punctuation marks etc...我有一个字符串,我将它转换为一个字符数组,然后我使用 LINQ 来选择字符数组中的不同字符,然后按降序对它们进行排序,但只捕获字符,而不是标点符号等...

Here is the code:这是代码:

string inputString = "The black, and, white cat";
var something = inputString.ToCharArray();
var txtEntitites = something.GroupBy(c => c)
                   .OrderByDescending(g => g.Count())
                   .Where(e => Char.IsLetter(e)).Select(t=> t.Key);

And the error message I get:我得到的错误信息:

  • Error CS1502: The best overloaded method match for `char.IsLetter(char)' has some invalid arguments (CS1502)错误 CS1502:“char.IsLetter(char)”的最佳重载方法匹配有一些无效参数 (CS1502)

  • Error CS1503: Argument '#1' cannot convert 'System.Linq.IGrouping<char,char>' expression to type `char' (CS1503)错误 CS1503:参数“#1”无法将“System.Linq.IGrouping<char,char>”表达式转换为“char”类型 (CS1503)

Any ideas?有任何想法吗? Thanks :)谢谢 :)

Try this:试试这个:

string inputString = "The black, and, white cat"; 
var something = inputString.ToCharArray();  
var txtEntitites = something.GroupBy(c => c)
                            .OrderByDescending(g => g.Count())
                            .Where(e => Char.IsLetter(e.Key))
                            .Select(t=> t.Key);

Note the Char.IsLetter(e.Key))注意Char.IsLetter(e.Key))

Another idea is to rearrange your query:另一个想法是重新排列您的查询:

varinputString = "The black, and, white cat"; 
var txtEntitites = inputString.GroupBy(c => c)
                              .OrderByDescending(g => g.Count())
                              .Select(t=> t.Key)
                              .Where(e => Char.IsLetter(e));

Also note you don't need the call to inputString.ToCharArray() since String is already an IEnumerable<Char> .另请注意,您不需要调用inputString.ToCharArray()因为String已经是IEnumerable<Char>

In your where clause, e in that context is your grouping, not the character.在您的 where 子句中, e在该上下文中是您的分组,而不是字符。 If you want to check if the character is a letter, you should be testing your key.如果您想检查字符是否为字母,则应该测试您的密钥。

//...
.Where(g => Char.IsLetter(g.Key))

I think this is what you are looking for我想这就是你要找的

string inputString = "The black, and, white cat";
var something = inputString.ToCharArray();
var txtEntitites = something.Where(e => Char.IsLetter(e))
                   .GroupBy(c => c)
                   .OrderByDescending(g => g.Count()).Select(t=> t.Key);
List<char> charArray = (
      from c in inputString
      where c >= 'A' && c <= 'z'
      orderby c
      select c
   ).Distinct()
   .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM