This is my first go at playing with Linq. So far it is pretty cool, but I wanted to share something because I found it painful.
I wanted query a list and then cast a anonymous type to a static type. I was not able to find anything on the net to help me with this (could be i just did not look in the right places) so i thought i would share my findings.
Below is the definition of the 'Sport' object
[Serializable]
public class Sport
{
public virtual Int32 SportID { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
Here is the code to query some data out of a list of sports List<Sport>
List sports = new List();
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;
The code below will show how to cast/convert from anonymous type to static type.
Sport sport = (Sport) query.First();
The code below will show how to cast back to a List<Sport>
List newSports = query.ToList();
Hope this helps someone else.
Till next time,
Posted
02-22-2008 9:19 AM
by
Derik Whittaker