I have an album task where I need to show images from a DB. Sup开发者_如何学运维posing there is no matching image in the DB, can I use DefaultIfEmpty
to select a default image?
EDIT: DefaultIfEmpty
already has a suitable overload.
You can't provide a default value to FirstOrDefault()
but you could always use:
// Select the first image, or a default otherwise
var image = query.FirstOrDefault() ?? defaultImage;
Or you could write your own overload of FirstOrDefault
which does accept a default, of course. Something like this:
public static T FirstOrDefault<T>(this IEnumerable<T> source,
T defaultValue)
{
// This will only ever iterate once, of course.
foreach (T item in source)
{
return item;
}
return defaultValue;
}
精彩评论