使用谓词统计单词

时间:2012-09-13 14:23:51

标签: c# predicate

我需要获得满足条件的字符串[]中指定的项目数。所以,我尝试了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)'有一些无效的参数< / p>

4 个答案:

答案 0 :(得分:4)

LINQ Count()方法不会将Predicate作为参数。在您的情况下,该方法采用类型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);

答案 1 :(得分:3)

试试这个:

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

当没有lambdas时这样做匿名方法定义一个方法(你的谓词):

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

使用它:

var result = books.Count(IsThisALongBookTitle);

答案 2 :(得分: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));

答案 3 :(得分:0)

您可以尝试使用

books.Count(a = > a.Length > 5);