Ciel
Ciel

Reputation: 17782

LINQ and Null Coallescing

I'm trying to get the null coallescing operator to work with a LINQ expression in ASP.NET MVC.

Here is my expression.

<%= Html.Encode(item.Ring.Keys.Single<ProjectOne.Key>( k => k.Literal.Value == "Class" ).KeyValue) %>

Basically, it finds an instance of the "Key" class based on the given Name, the name being the title, the result being the Value of the Key. I want to return a null string if it doesn't find a matching key.

Upvotes: 0

Views: 160

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503749

How about:

item.Ring.Keys
    .Where(k => k.Literal.Value == "Class")
    .Select(k => k.KeyValue)
    .SingleOrDefault();

That's assuming you want a null reference if it's not found. If you're rather have an empty string, just add ?? "" at the end:

item.Ring.Keys
    .Where(k => k.Literal.Value == "Class")
    .Select(k => k.KeyValue)
    .SingleOrDefault() ?? "";

There's another option which I don't like as much:

(item.Ring.Keys
     .SingleOrDefault(k => k.Literal.Value == "Class") 
         ?? new ProjectOne.Key { KeyValue = null }).KeyValue;

Upvotes: 2

Related Questions