Freigeben über


Casting with Linq

I've been working with Linq lately and thought I would post 2 examples on casting with Linq.  Most of the ways that you get data back from linq is in the IEnumerable<> type.  So, here's two ways to cast to an object that you can use:

Linq to SQL

Once you create your dbml file it will generate a class based on a table or your own custom class.  Once this is done, you can do the following to get your strongly typed object back:

LinqDataContext dataContext = new LinqDataContext(myConnectionString);
return dataContext.MyStoredProcedure().ToList();

One thing to remember - make sure that the method that Visual Studio creates for your stored procedure also returns the strongly typed class instead of the <T> (for whatever T is) that it might try to create.

Linq to XML

With Linq to Xml, just create your XDocument object by loading in the xml file.  Then you can do this (for whatever your StrongType happens to be):

XDocument myXmlDoc = XDocument.Load("somefile.xml");
IEnumerable<StrongType> items = from item in myXmlDoc (and whatever else your statement is to select items)
                                                    select new StrongType { StrongTypeProperty = item.Property};
return items.ToList();