【问题标题】:LINQ C# Selecting characters from stringLINQ C#从字符串中选择字符
【发布时间】:2012-08-22 02:53:34
【问题描述】:

我有一个字符串,我将其转换为 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”类型 (CS1503)

有什么想法吗?谢谢:)

【问题讨论】:

标签: c# linq


【解决方案1】:

试试这个:

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>

【讨论】:

  • 谢谢你 :) 谢谢你没有抱怨我问问题哈!
  • 您的问题简短、简洁,并提供了错误消息的详细信息,因此我投了赞成票 :-)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    List<char> charArray = (
          from c in inputString
          where c >= 'A' && c <= 'z'
          orderby c
          select c
       ).Distinct()
       .ToList();
    

    【讨论】:

      【解决方案4】:

      我想这就是你要找的东西

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        • 2016-07-08
        相关资源
        最近更新 更多