ronaldwidha
ronaldwidha

Reputation: 1345

improving readiblity and be slightly less explicit using Linq

All,

I've got the following code, and looking into ways to improve its readibility (and remove the null check) by using Linq.

var activePlan = CurrentPlans.First();
var activeObjectives = activePlan != null ? activePlan.Objectives : null;

The closest I get is the following:

var activeObjectives = CurrentPlans.Take(1).Select(x => x.Objectives);

which gives me a collection of x.Objectives instead of Objectives. Any ideas?

Upvotes: 0

Views: 65

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134521

I'd write if like this:

var activeObjectives = CurrentPlans.Select(x => x.Objectives).FirstOrDefault();

This way, it's easier to work out the intention by the use of methods. Take the first set of objectives, otherwise the default (null assuming Objectives refers to a reference type). Using SelectMany() for this case isn't the best choice IMO.

Upvotes: 4

ronaldwidha
ronaldwidha

Reputation: 1345

oh got it:

var activeObjectives = CurrentPlans.Take(1).SelectMany(x => x.Objectives)

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

Upvotes: 1

Related Questions