优雅的方式来计算的字母数字字符的字符串?字符串、字母、字符、优雅

2023-09-03 05:36:21 作者:情的尽头还是散

我要寻找一个优雅的方式,preferably短LINQ EX pression,计算有多少个字母数字字符指定字符串中包含。

I am looking for an elegant way, preferably a short linq expression, to count how many alphanumeric chars a given string contains.

在'无聊'的方式我现在做的是这样的:

The 'boring' way I do it now is this:

int num = 0;
for (int i = 0; i < password.Length; i++)
{
    if (!char.IsLetterOrDigit(password, i))
    {
        num++;
    }
}
if (num < MinRequiredNonAlphanumericCharacters)
    return false;

这是相当短了,但我相信有一些LINQ魔术这可以在更短的,同样可以理解的EX pression做,对不对?

This is rather short already, but I am sure with some linq magic this can be done in an even shorter, equally understandable expression, right?

推荐答案

这里的快速和肮脏的LINQ的方式来获得字母放大器;数字计数:

Here's the quick and dirty LINQ way to get the letter & digit count:

password.Count(char.IsLetterOrDigit)

这是多的,你在做什么,直接复制:

This is more of a direct copy of what you're doing:

password.Count(c => !char.IsLetterOrDigit(c))