I need to get the count of items specified in a string[] which satisfies my condition. So, I tried Predicate and defined my condition using the same. But my code is not working. Can anyone please help me?
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);
When I run this, it shows a compile time error. Please see below:
‘string[]’ does not contain a definition for ‘Count’ and the best extension method overload ‘System.Linq.Enumerable.Count(System.Collections.Generic.IEnumerable, System.Func)’ has some invalid arguments
The LINQ
Count()method does not take aPredicateas a parameter. In your case the method takes a delegate of typeFunc<string, bool>. So there are a couple ways you can fix your code, the simplest would probably be to do what others have suggested and use a lambda. Or, using your original code just changePredicate<string>toFunc<string, bool>: