Syed Salman Raza Zaidi Syed Salman Raza Zaidi - 3 months ago 15
C# Question

foreach on IEnumerable or IList

I am using LINQ with Entity framework to joining three tables and I am returning

IList
interface.

I want to apply
foreach
loop on this returned value so I can populate values in my model.

This is how I am joining:

public IList GetData(long Id)
{
//var q = dataContext.tblUsers.AsEnumerable().Join(dataContext.tblUsersProfiles.AsEnumerable(),)
var query = from u in dataContext.tblUsers
join p in dataContext.tblUsersProfiles on u.ProfileId equals p.Id
join c in dataContext.tblComments on u.Id equals c.Commentedby

where c.Id == Id
select new { u.Firstname, u.Lastname, p.ProfilePicPath, c.Comment, c.CommentDate };

return query.ToList();
}


I want to populate these values in my List of Model. I have tried this:

var lst = repository.GetDate(Id);
foreach (var item in lst)
{

}


But I am unable to access item
Firstname
/
Lastname
etc.

I also tried using object
item
and
object[] item
but they both are not working too.

How can I apply a
for
each
on
IList`?

It will work fine If I'm be able to return
DataTable
instead of
IList
in this case.

Answer

Your are creating an anonymous type. Just define a class for the result of your query, then the return type of your function should be like this:

public IList<YourClassName> GetData(long Id)
{

}

Set class values like this:

select new YourClassName 
{
    Firstname = u.Firstname,
    Lastname = u.Lastname, 
    ProfilePicPath = p.ProfilePicPath,
    Comment = c.Comment,
    CommentDate = c.CommentDate
};