Hemant Kumar
Hemant Kumar

Reputation: 4611

Can we use DefaultIfEmpty to show a default image?

I have an album task where I need to show images from a DB. Supposing there is no matching image in the DB, can I use DefaultIfEmpty to select a default image?

Upvotes: 1

Views: 165

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501163

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

Upvotes: 1

Related Questions