skiskd
skiskd

Reputation: 423

How to loop through var object collection in C#?

I have collection generated from linq (group by query). this generated list and collection I want to iterate the loop for each key, I have following code which generate list of object by grouping and now I want loop through

var objList=from p in objConfigurationList
group p by p.UserID into g
select new { UserID=g.Key, ReportName=g.ToList() };

foreach (object oParam in objList)
{

}

so how can I access key and reportname list inside this foreach. how to write foreach for that?

Upvotes: 3

Views: 10104

Answers (2)

Sinatr
Sinatr

Reputation: 21999

You could also use a small extension method (credits):

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
    foreach (var item in @this)
        action(item);
}

Then you can do

objList.Foreach(oParam =>
{
    ... // your code here, e.g. Console.WriteLine(oParam.UserID)
}

It's really good in method-syntax linq.

Upvotes: 4

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Use var instead of object. The select new creates an anonymous type:

foreach (var oParam in objList)
{
    Console.WriteLine(oParam.UserID);
}

Upvotes: 11

Related Questions