How to create a List from an Entity Framework query result

c# c#-4.0 entity-framework

Question

How to Put the following query result into a List

var  result = from c in sb.Swithches_SW_PanalComponents
                     select new { c.ID,c.SW_PanalComponents.ComponentsName,c.ComponentValue };
1
3
1/10/2012 3:18:10 AM

Accepted Answer

FINAL EDIT

Based on your last comment, this is all you ever needed

List<Swithches_SW_PanalComponents> result = 
                                  sb.Swithches_SW_PanalComponents.ToList();

which of course is identical to

var result = sb.Swithches_SW_PanalComponents.ToList();

EDIT

Based on your comments, I think this is what you want:

List<SW_PanalComponents> result = sb.Swithches_SW_PanalComponents
                  .Select(c => new SW_PanalComponents { /* initialize your fields */ })
                  .ToList();

END EDIT

The ToList method is what you want. But consider using dot notation. For simple queries like this, it's much cleaner and trimmer.

var result = sb.Swithches_SW_PanalComponents
                  .Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
                  .ToList();

Also note that, if you're just trying to execute your query immediately, and only need to enumerate over it, you can also call AsEnumerable()

var result = sb.Swithches_SW_PanalComponents
                  .Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
                  .AsEnumerable();

The advantage here is that result is a less specific type—IEnumerablt<T>.

6
1/11/2012 1:21:31 AM

Popular Answer

Like this:

var  result =(from c in sb.Swithches_SW_PanalComponents
                     select new 
                     { c.ID,
                       c.SW_PanalComponents.ComponentsName,
                       c.ComponentValue 
                     }).ToList();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow