major
major

Reputation: 323

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 };

Upvotes: 5

Views: 39565

Answers (3)

Adam Rackis
Adam Rackis

Reputation: 83358

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

Upvotes: 9

major
major

Reputation: 323

That what i came with finally:

  List<Swithches_SW_PanalComponents> MyList = new List<Swithches_SW_PanalComponents>();
        var Result = from all in sb.Swithches_SW_PanalComponents
                     select all
                     ;
        MyList.AddRange(Result.ToList<Swithches_SW_PanalComponents>());

Upvotes: 0

Icarus
Icarus

Reputation: 63956

Like this:

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

Upvotes: 5

Related Questions