tags:

views:

43

answers:

2

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?

+1  A: 

oh got it:

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

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

ronaldwidha
Is someone here trying to get `Self-Learner` badge? :D
ŁukaszW.pl
+4  A: 

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.

Jeff M