7

我有一个字符串,我将其转换为 char 数组,然后使用 LINQ 选择 char 数组中的不同字符,然后按降序对它们进行排序,但只捕获字符,而不是标点符号等...

这是代码:

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);

我得到的错误信息:

  • 错误 CS1502:“char.IsLetter(char)”的最佳重载方法匹配有一些无效参数 (CS1502)

  • 错误 CS1503:参数“#1”无法将“System.Linq.IGrouping<char,char>”表达式转换为“char”类型 (CS1503)

有任何想法吗?谢谢 :)

4

4 回答 4

9

试试这个:

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);

注意Char.IsLetter(e.Key))

另一个想法是重新排列您的查询:

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

另请注意,您不需要调用,inputString.ToCharArray()因为String已经是IEnumerable<Char>.

于 2012-08-22T02:56:29.357 回答
2

在您的 where 子句中,e在这种情况下是您的分组,而不是字符。如果要检查字符是否为字母,则应测试密钥。

//...
.Where(g => Char.IsLetter(g.Key))
于 2012-08-22T02:56:10.567 回答
2
List<char> charArray = (
      from c in inputString
      where c >= 'A' && c <= 'z'
      orderby c
      select c
   ).Distinct()
   .ToList();
于 2016-11-02T14:42:03.290 回答
1

我想这就是你要找的

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);
于 2012-08-22T04:03:26.287 回答