What is the difference between
select(a=>a) and select(a=>a.value)
? .Where do i need the second one?
views:
94answers:
4You need the second one whenever you want to access solely the "value" property of the object "a".
Select applies the given function to all values in your collection.
a => a
therefore maps an element to itself and hence doesn't have any effect.
a => a.value
maps each element to its value
property.
The first one (select(a => a)
) is redundant - it doesn't really do anything.
The second one (select(a => a.value
) is called a Projection. It projects a list of a
(whatever that is) to a list of its values. You haven't told us what a
or its value is, but it looks like a field or a property...
You've already received some pretty solid replies, and I'm not going to argue with those other answers, they're fine, but I want to try a different approach here.
If you've really not noticed the difference between selecting whatever object, and selecting whatever property on whatever object - and it is quite a fundamental difference - I suspect, that your a
may be a Nullable<T>
. I'm suspecting this, because if a
is nullable, a lot of the times you'll be able to use a
and a.Value
interchangeably, and might not notice the difference.
A Nullable<T>
wraps a type that isn't nullable, into a class that can be null. Getting and setting a value to this property, will not directly assign the wrapper class, but it will actually be assigning (or getting) a value to its Value
property. A Nullable<T>
also comes with a boolean property HasValue
.
If your database contains a bit field, say, and that bit field happens to allow null values, then Linq to SQL (say), will map that to a Nullable<bool>
(shorthand, bool?
). If your table allows null, but never actually contains any null values, you might not notice the difference between .Select(myNullableBool => myNullableBool)
(which is, as someone has pointed out, redundant), and .Select(myNullableBool => myNullableBool.Value)
, but the difference here will actually be that the latter returns an IEnumerable<bool>
, whereas the former returns IEnumerable<Nullable<bool>>
. The latter assumes the bool will have a value, so if you want to play safe, you should do .Where(mNB => mNB.HasValue).Select(mNB => mNB.Value)
(there's also a GetValueOrDefault
method that you could use in your Select). If a null value for a flag doesn't make sense in your model, then its datatype should be a boolean, and not a nullable boolean. In that case you want to make sure you select .Value
and not the entire nullable, as a nullable boolean cannot be assigned to a boolean variable.
Your code doesn't reveal enough info, to be able to judge if this reply is relevant here, but I'm guessing this might be the real cause of your question. If it isn't (or actually even if it is), what the other guys have replied is still true in general.