DEFAULT VALUE WHEN USING SINGLEORDEFAULT()

Tanuj Kumar

Total Post:134

Points:940
Posted by  Tanuj Kumar
C# 
C#
 1307  View(s)
Ratings:
Rate this:

I have a simple class like:

class Color

{

    public int ID { get; set; }

    public string ColorName { get; set; }

}

and then create a collection of these objects:

List<Color> ColorList;

I'd like to then query this collection with LINQ.

Color selected = ColorList.SingleOrDefault(a => a.ID == someVariable);

My collection will have several colors, all with unique IDs, and one color that I'd want to be the default. What I'm looking for is the ability to specify what is returned when someVariable does not match any ID in the collection. Is this possible, or does SingleOrDefault only return null when a match isn't found?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Default Value when using SingleOrDefault()

    Hi  tanuj, 

    Yo can do like this:

    Use ?? (null coalescing operator)

    Color selected = ColorList.SingleOrDefault(a => a.ID == someVariable) ??

                              new Color {Id = 1234, ColorName = "Blue"}; //Default value

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!