SAK
SAK

Reputation: 25418

Equivalent to search within IEnumerable with LINQ

Is there a shorter, elegant way to write the following using LINQ?

 var actorName = string.Empty;
 foreach (var myProperty in myProperties)
 {
       if (myProperty .PropertyName == "ActorName")
       {
             actorName = myProperty .PropertyValue;
             break;

       }

  }

Upvotes: 0

Views: 1387

Answers (3)

Cory Nelson
Cory Nelson

Reputation: 30001

Pure LINQ version, for the hell of it, though I'd prefer Simon's answer.

var actorName = myProperties
    .Where(x => x.PropertyName == "ActorName")
    .Select(x => x.PropertyValue)
    .Concat(new[]{ string.Empty })
    .First();

Upvotes: -1

Simon Whitehead
Simon Whitehead

Reputation: 65077

In addition to Jeroen's answer.. its safer to check for null first.. since FirstOrDefault returns null when there is nothing that matches:

var actor = myProperties
            .FirstOrDefault(x => x.PropertyName == "ActorName");

if (actor != null)
    actorName = actor.PropertyValue;

Upvotes: 2

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44459

var actorName = myProperties
                .FirstOrDefault(x => x.PropertyName == "ActorName")
                .PropertyValue;

This would give a NPE if nothing could be found though (FirstOrDefault returns null as default).

To combat this, use two statements instead:

var actor = myProperties
                .FirstOrDefault(x => x.PropertyName == "ActorName");

var actorName = actor == null ? string.Empty : actor.PropertyValue; 

Upvotes: 5

Related Questions