Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq & Boolean Function

Tags:

c#

linq

boolean

Is there any way one can apply a function with signature

bool IsOdd(int number);

to an array of integers and return whether any given integer in that array is odd in a single instruction? I know I can use

return (array.Where(IsOdd).Count() > 0);

but that implies calling two methods and making a comparison... Isn't there really a shorter way to achieve the same?

like image 757
User Avatar asked Aug 27 '11 20:08

User


People also ask

What is LINQ used for?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

Is LINQ better than SQL?

The main difference between LINQ and SQL is that LINQ is a Microsoft . NET framework component, which adds native data querying capabilities to . NET languages, while SQL is a standard language to store and manage data in RDBMS.

Is LINQ only for C#?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.

Is LINQ popular in C#?

The primary reason that LINQ was introduced with C# 3.0 was to reduce the amount of coding that object retrieval required, in comparison to more traditional for each loops, and it is largely due to this reason that LINQ has gained such popularity within the field.


1 Answers

Yes.

To start with you could use the form of Count which takes a predicate:

return array.Count(IsOdd) > 0;

... but you don't want to do that. That code is still expressing a numerical comparison which is unnecessary. You want to ask if any item in the array is odd. In other words:

return array.Any(IsOdd);

Not only is this more expressive - it's also potentially much faster. As soon as Any finds a match, it will return true - whereas Count would have to iterate over the whole array to find out exactly how many matches there are.

Basically, whenever you see a LINQ query using Count() > 0 you should think about using Any instead. In some cases with expression-tree-based queries such as LINQ to SQL it may not make a performance difference (if the query optimizer has visibility of the comparison with 0) but in LINQ to Objects it certainly can.

like image 155
Jon Skeet Avatar answered Nov 06 '22 10:11

Jon Skeet