Flexabust Bergson Flexabust Bergson - 6 months ago 20
C# Question

Iterate through a List<dynamic>

I have an Entity Framework request to retrieve many different informations, using several inner joins, so I use a dynamic List as a return type, but I can't seem to find a way to make it work when iterating through it.

I made a request with 4 tables but I'll take another example to simplify, say I have tables


var result = from r in Room
join k in Kitchen on r.idKitchen=k.id
where (r.id == myIDPassedAsParameter)
select new { rId = r.id, kId = k.id}

now when trying to access it I do the following :

foreach (var r in result)
foreach (var item in r)
Console.WriteLine(item.rId + " " + item.kId);


I keep getting a conversion exception on the second foreach. I couldn't find any way to fix this. I used it originally because my results returned are of anonymous type, so that's what I found to make the return possible.


Answer Source

As I stated in the comment, I'd do this

private class RoomKitchenPair
        public int RoomId { get; set; }

        public int KitchenId { get; set; }

var result = (from r in Room
         join k in Kitchen on r.IdKitchen equals k.Id
         where (r.Id == myIDPassedAsParameter)
         select new RoomKitchenPair { RoomId= r.Id, KitchenId = k.Id})

foreach (var r in result)
    Console.WriteLine(r.RoomId + " - " + r.KitchenId );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download