Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an Entity Framework query result into a List

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 };
like image 265
major Avatar asked Jan 10 '12 03:01

major


People also ask

How do I select specific columns in Entity Framework?

We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns. There. That looks better.


2 Answers

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>.

like image 175
Adam Rackis Avatar answered Sep 28 '22 23:09

Adam Rackis


Like this:

var  result =(from c in sb.Swithches_SW_PanalComponents
                     select new 
                     { c.ID,
                       c.SW_PanalComponents.ComponentsName,
                       c.ComponentValue 
                     }).ToList();
like image 35
Icarus Avatar answered Sep 28 '22 23:09

Icarus