简体   繁体   English

使用 LINQ 计算字符串中字母的出现次数

[英]Count the occurrences of a letter in a string with LINQ

Im trying to implement a piece of code that will return the count of the specified letter in a string.我试图实现一段代码,它将返回字符串中指定字母的计数。 I can do it with a for loop but I find it more elegant of a solution to use LINQ expressions.我可以使用 for 循环来做到这一点,但我发现使用 LINQ 表达式的解决方案更优雅。 Here is my code:这是我的代码:

public static int CountAs(string countA)
{

    var test = count.Select(x => x == 'a').Count();
        
    return test;

}

Im trying to count how many lower case letter a's exist in the countA parameter.我试图计算countA参数中存在多少个小写字母a。 What is wrong with my code?我的代码有什么问题?

Thank you in advance!先感谢您!

UPDATE更新

The method I should be using is the Where method instead of the Select method.我应该使用的方法是Where方法而不是Select方法。 Using this fixed my issue:!使用它解决了我的问题:! the function can be rewritten as: function 可以重写为:

public static int CountAs(string input)
{
   return input.Where(x => x == 'a').Count();
}

Alternatively, you could just use the Count method to directly filter out the desired letter:或者,您可以只使用 Count 方法直接过滤掉所需的字母:

public static int CountAs(string input)
{
   return input.Where(x => x == 'a').Count();
}

Thank you everyone that came to the rescue!!感谢所有前来救援的人!!

Use .Where instead of .Select .使用.Where而不是.Select .Where finds items that match your criteria, whereas .Select tells it how to return said items if you need to transform them. .Where查找符合您的条件的项目,而.Select告诉它如何返回所述项目,如果您需要转换它们。

You should use .Count() with a predicate.您应该将.Count()与谓词一起使用。 The .Count() method is used to do data calculation and based on condition (predicate). .Count()方法用于根据条件(谓词)进行数据计算。

.Count()

Returns the number of elements in a sequence.返回序列中元素的数量。

Meanwhile .Select() is used for data projection / display.同时.Select()用于数据投影/显示。

.Select()

Projects each element of a sequence into a new form.将序列的每个元素投影到新形式中。

Thus, your output count with .Select() will return the length of your string.因此,带有.Select()的 output 计数将返回字符串的长度。

SOLUTION: Calculates the number of lower 'a's only in the string as requested from Post Owner.解决方案:根据帖子所有者的要求,仅计算字符串中较低的 'a' 的数量。

public static int CountLowerAs(string input)
{
    return input.Count(x => x == 'a');
}

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

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