开发者

Can we use DefaultIfEmpty to show a default image?

开发者 https://www.devze.com 2023-01-27 23:39 出处:网络
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 alr

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消