Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Simple Linq to Object example with Casting

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
Filed under: , ,

[Advertisement]

Comments

Garry Shutler wrote re: Simple Linq to Object example with Casting
on 02-22-2008 10:45 AM

If I need the query outside the scope I've generally made the query go straight into the type I need:

IEnumerable<Sport> sports = from....etc

If you need to make it of a different type I make each result of a given type:

IEnumerable<SpecificClass> list = from s ... etc

select new SpecificClass(s.Name, s.Age);

Christopher Bennage wrote re: Simple Linq to Object example with Casting
on 02-22-2008 10:56 AM

Good stuff.

Daily Bits - February 23, 2008 | Alvin Ashcraft's Daily Geek Bits wrote Daily Bits - February 23, 2008 | Alvin Ashcraft's Daily Geek Bits
on 02-23-2008 12:06 PM

Pingback from  Daily Bits - February 23, 2008 | Alvin Ashcraft's Daily Geek Bits

Igor Ostrovsky wrote re: Simple Linq to Object example with Casting
on 02-24-2008 9:26 PM

The code is actually *not* casting from an anonymous type to a user-defined type.

The objects you add to the sports list are already of type Sport, not of an anonymous type. The following constructs an object of type Sport, and also immediately initializes its properties:

new Sport { SportID = 5, Name = "Sport 5", Description = "Sport Desc 5" }

To construct an object of an anonymous type, you need to do the following:

new { SportID = 5, Name = "Sport 5", Description = "Sport Desc 5" }

If you change your code sample so that it really constructs objects of an anonymous type, you'll see that the cast no longer works.

calvin wrote re: Simple Linq to Object example with Casting
on 03-27-2009 1:39 PM

What Igor said is true. There is no simple cast from an anonymous type to a custom object. According to this MSDN article: msdn.microsoft.com/.../bb397696.aspx, it cannot be cast to any type except for object.  You have to explicitly create new objects.

Zimmer wrote re: Simple Linq to Object example with Casting
on 11-01-2009 1:40 PM

Thanks...this helped me. New to Linq & lovin it uses!

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)