15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1066 ❘ ChaPTer 36 business ApplicAtiOns with wpf<br />

}<br />

}<br />

public IEnumerable Years<br />

{<br />

get<br />

{<br />

F1DataContext.Data = data;<br />

return (from r in data.Races<br />

orderby r.Date ascending<br />

select<br />

new Championship<br />

{<br />

Year = r.Date.Year,<br />

}).Distinct();<br />

}<br />

}<br />

code snippet Formula1Demo/TreeUC.xaml.cs<br />

The Championship class has a simple automatic property for the year. The Races property is of type<br />

Lazy. The Lazy class is new with .<strong>NET</strong> 4 for lazy initialization. With a<br />

TreeView control, this class comes in very h<strong>and</strong>y. If the data behind the tree is large <strong>and</strong> you do not want<br />

to load the full tree in advance, but only when a user makes a selection, lazy loading can be done. With<br />

the constructor of the Lazy class, a delegate Func is used. With this delegate,<br />

IEnumerable needs to be returned. The implementation of the Lambda expression, assigned to<br />

the delegate, uses a LINQ query to create a list of F1Race objects that have the Date <strong>and</strong> Country<br />

property assigned:<br />

public class Championship<br />

{<br />

public int Year { get; set; }<br />

public Lazy Races<br />

{<br />

get<br />

{<br />

return new Lazy(() =><br />

{<br />

return from r in F1DataContext.Data.Races<br />

where r.Date.Year == Year<br />

orderby r.Date<br />

select new F1Race<br />

{<br />

Date = r.Date,<br />

Country = r.Circuit.Country<br />

};<br />

});<br />

}<br />

}<br />

}<br />

code snippet Formula1Demo/Championship.cs<br />

The F1Race class again defines the Results property that uses the Lazy type to return a list of<br />

F1RaceResult objects:<br />

public class F1Race<br />

{<br />

public string Country { get; set; }<br />

public DateTime Date { get; set; }<br />

public Lazy Results<br />

{<br />

get<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!