2012-09-13 106 views
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); 

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

“串[]”不包含“计数”和最佳的扩展方法过载“System.Linq.Enumerable.Count(System.Collections.Generic.IEnumerable,System.Func定义)”有一些无效参数

+2

请加德泰ls为什么它不起作用 – CharlesB

+1

我已经编辑过你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

+2

而不是像这样使用匿名委托,你可以使用lambda'books.Count(book => book.Length> 5)''''''''' –

回答

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

完美谢谢! – user972255

2

试试这个:

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

做这件事时没有lambda表达式匿名方法定义一个方法(您谓语):

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

使用它:

var result = books.Count(IsThisALongBookTitle); 
+0

你可以让我知道如何使用Predicate来做到这一点。 – user972255

+0

这实际上是一个谓词,但我编辑了我的帖子,以显示这是如何工作的,没有lambda表达式和匿名方法。 – Spontifixus

+0

事实上,这是_is_一个'Func ',但它与'Predicate '具有相同的方法签名...... – Spontifixus

0

您可以

books.Count(a = > a.Length > 5); 
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)); 
+0

感谢您的帮助。此外,第一个没有工作,但其他2工作正常。它给出了这个错误,'System.Array'不包含'AsEnumberable'的定义,并且没有找到接受类型'System.Array'的第一个参数的扩展方法'AsEnumberable'(你是否缺少using指令或程序集参考?) – user972255

+0

你引用了'System.Core'程序集并使用了正确的namespances吗?尝试'new List {“c”,“b”,“a”}。OrderBy(s => s);'如果代码不能编译,那么你必须检查using和引用程序集。 –