开发者

Can we use DefaultIfEmpty to show a default image?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜