Gerrie Schenck
Gerrie Schenck

Reputation: 22368

How to convert an anonymously typed List to List<T>?

This simple Linq query:

from c in mycontext.Customers
join o in mycontext.Orders on c.CustomerId equals o.CustomerId
where o.Status == 1
select new {c, o}

will result in

List<{c:Customer, o:Order}>

after calling ToList().

What's the easiest way of converting this anonymously typed list into a list of customers (List<Customer>)?

EDIT: I need the orders for an extra condition, I've changed my original question.

Upvotes: 2

Views: 429

Answers (5)

John Nicholas
John Nicholas

Reputation: 4836

why not just use .ToList<Customers>()

and don't select the orders - you don't need them after the join.

List<Customer> custList =  (from c in mycontext.Customers
    join o in mycontext.Orders on c.CustomerId equals o.CustomerId
    where o.Status == 1
    select c).ToList<Customer>();

Upvotes: 1

cyberzed
cyberzed

Reputation: 2076

var ledger = from c in mycontext.Customers
                 join o in mycontext.Orders on c.CustomerId equals o.CustomerId
                 where o.Status == 1
                 select new {c, o};

var customers = (from row in ledger select row.Customer).Distinct().ToList();

That would be my sorta bidding on a solution (inclusive mispellings etc.) :)

Upvotes: 0

user57508
user57508

Reputation:

very basic approach, as you explecitely asked "What's the easiest way of converting this anonymously typed [...]":

var anonymousEnumerable = from c in mycontext.Customers
                          join o in mycontext.Orders on c.CustomerId equals o.CustomerId
                          select new
                          {
                              c,
                              o
                          };
var typedEnumerable = anonymousList.Select(item => item.c).Distinct(); // either referenceCheck or you supply an IEqualityComparer<Customer>-implementation

maybe you can give us some more information an what you want exactly to achieve!

Upvotes: 1

Paul
Paul

Reputation: 5576

Do you need both the properties? If so step through the list and instantiate each curstomer...

Something like

 List<Customer> customers = new List<Customer>();
 foreach(item in linqQuery.ToList())
 {

     customers.Add(item.c);
     //do something with the Order here...
 }

Upvotes: 0

RoelF
RoelF

Reputation: 7573

result.Select(o => o.Customer).ToList();

Is this what you mean?

Upvotes: 7

Related Questions