0

我需要获取满足我条件的字符串 [] 中指定的项目数。所以,我尝试了 Predicate 并使用它定义了我的条件。但是我的代码不起作用。谁能帮帮我吗?

string[] books = new string[] { "Java", "SQL", "OOPS Concepts", "DotNet Basics"};

Predicate<string> longBooks = delegate(string book) { return book.Length > 5; };
int numberOfBooksWithLongNames = books.Count(longBooks);

当我运行它时,它显示编译时错误。请看下面:

'string[]' 不包含 'Count' 的定义,并且最佳扩展方法重载 'System.Linq.Enumerable.Count(System.Collections.Generic.IEnumerable, System.Func)' 有一些无效参数

4

4 回答 4

4

尝试这个:

var result = books.Count(x => x.Length > 5);

在没有 lambda 匿名方法的情况下执行此操作时,请定义一个方法(您的谓词):

public bool HasLongTitle(string book)
{
    return book.Length > 5;
}

使用它:

var result = books.Count(HasLongTitle);
于 2012-09-13T14:27:09.827 回答
4

LINQCount()方法不采用 aPredicate作为参数。在您的情况下,该方法采用 type 的委托Func<string, bool>。所以有几种方法可以修复你的代码,最简单的可能是按照其他人的建议并使用 lambda。或者,使用您的原始代码只需更改Predicate<string>Func<string, bool>

string[] books = new string[] { "Java", "SQL", "OOPS Concepts", "DotNet Basics"};

Func<string, bool> longBooks = delegate(string book) { return book.Length > 5; };
int numberOfBooksWithLongNames = books.Count(longBooks);
于 2012-09-13T14:34:16.797 回答
1

有两个问题

string[]' does not contain a definition for 'Count' and the best extension method
 overload 'System.Linq.Enumerable.Count<TSource>
(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,bool>)' 
has some invalid arguments

Argument 2: cannot convert from 'System.Predicate<string>' to 
'System.Func<string,bool>'

这些解决方案有效

int numberOfBooksWithLongNames = books.AsEnumberable().Count(s => longBooks(s));
int numberOfBooksWithLongNames = new List<string>(books).Count(s => longBooks(s));
int numberOfBooksWithLongNames = books.Count(s => longBooks(s));
于 2012-09-13T14:36:07.180 回答
0

你可以试试

books.Count(a = > a.Length > 5);
于 2012-09-13T14:28:07.340 回答