R4D4
R4D4

Reputation: 1402

How can I return a specific value for LINQ if nothing is found?

It seems I've stumbled my way onto LINQ and have only just managed to see its usefulness. I'm unsure if I'm asking too much of it, or if I'm not doing things correctly. I have the following clumsy code,

class CStation{
    public String Make;
    public List<ulong> TunedStations;
}

List<List<ulong>> mStations=(from t in Radios where t.Make==aMake select t.TunedStations).ToList();
if(mStations.Count!=0)
    return mStations[0];
return null;

Functional yes, but could I some how do this with LINQ?

Upvotes: 2

Views: 302

Answers (2)

Preet Sangha
Preet Sangha

Reputation: 65466

You can use this :

var myDefault = ......;

return (from t in Radios 
        where t.Make==aMake 
        select t.TunedStations)
       .FirstOrDefault() ?? myDefault ; 

or as a lambda

    var myDefault = ......;
    
    return Radios.Where(t => t.Make == aMake)
           .FirstOrDefault() ?? myDefault ; 

These will return the first item in the collection or your default (or just omit ?? myDefault if you want to return null)

Upvotes: 2

fenix2222
fenix2222

Reputation: 4730

Just use

return (from t in Radios where t.Make==aMake select t.TunedStations).FirstOrDefault(); 

Upvotes: 6

Related Questions