3

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?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
skiskd
  • 423
  • 2
  • 9
  • 20

2 Answers2

11

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

foreach (var oParam in objList)
{
    Console.WriteLine(oParam.UserID);
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
4

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.

Community
  • 1
  • 1
Sinatr
  • 20,892
  • 15
  • 90
  • 319