While implementing a condition in my
project I got confused because of the use of Where & Select in Linq .
The scenario was
My requirement was to find the count of
File types with is satisfy the condition. Initially I have tried with select
& it is always return count as ‘1’ instead of ‘0’. After a long analyses I
found my foolish mistake.
I searched the difference between the two
operations find the exact result.
The scenario was
int _finalcount =
ComponentFiles.Where(x => x.FileLocationTypeID.HasValue && x.FileLocationTypeID.Value
== 4).Count();
int _finalcount =
ComponentFiles.Select(x => x.FileLocationTypeID.HasValue &&
x.FileLocationTypeID.Value == 4).Count();
Select is a projection, so what you get is the
expression x=> x. FileLocationTypeID.Value == 4 evaluated for each
element in ComponentFiles on the server. i.e. lots of true/false values (the
same number as your original list). If you look the select will return
something like IEnumerable<bool> (because the type of x.FileLocationTypeID.Value
== 4 is a bool).
Where filters the results, returning an enumerable of
the original type (no projection).
Simply say Where() is a filter.Select() selects a different piece of data
No comments:
Post a Comment