views:

63

answers:

1

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.

+1  A: 

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;
Jon Skeet
Well, it needs to be in the Lamda expression. I can't rightly use the full LINQ syntax in the View. That's what I can't seem to get to work right.
Stacey
Sorry, I misunderstood. Yes, this works. I'm wondering if there is a simpler way to do it, to where that object will always return something appropriate if it isn't found...
Stacey
I'll edit with another option.
Jon Skeet
This worked perfectly. It was absolutely gorgeous.
Stacey