Tuesday, October 26, 2010

Simple Linq to Object example without Casting

I found this discussion related to casting the result of a LINQ query to a static object at http://devlicio.us/blogs/derik_whittaker/archive/2008/02/22/simple-linq-to-object-example-with-casting.aspx Since it was not possible to post a comment I decided to write a blog entry on my blog.

The example given at the above page gives the following code:


List<Sport > sports = new List <Sport>();
sports.Add(new Sport { SportID = 1, Name = "Sport 1", Description = "Sport Desc 1" });
sports.Add(new Sport { SportID = 2, Name = "Sport 2", Description = "Sport Desc 2" });
sports.Add(new Sport { SportID = 3, Name = "Sport 3", Description = "Sport Desc 3" });
sports.Add(new Sport { SportID = 4, Name = "Sport 4", Description = "Sport Desc 4" });
sports.Add(new Sport { SportID = 5, Name = "Sport 5", Description = "Sport Desc 5" });

var query = from s in sports
         where s.Name == "Sport 2"
         select s;

Sport sport = (Sport)query.First();


I would like to note that you could rewrite the above statements using lambdas:

Sport sport = sports.Where(s => s.Name == "Sport 2").First();

No "casting" is required.

No comments:

Post a Comment