# Improve grouping in LINQ

I have a collection (Child Collection) on which I am performing some operation to make another collection (Parent Collection). But that I do in a dirty foreach loop. I want to do it in an elegant way.

GroupInfo grpInfo;
List<GroupInfo> lstGroupInfo = new List<GroupInfo>();
{
{

grpInfo.Rural = true;
grpInfo.Urban = true;

}
else
{
grpInfo = new GroupInfo();

grpInfo.Rural = true;
grpInfo.Urban = true;

}
}


GroupInfo class is:

public class GroupInfo
{
{
get;
set;
}

{
get;
set;
}

public int? LocationID
{
get;
set;
}
}


I want to do it in LINQ lambda way.

• You need to tidy up the code sample, it's very difficult to figure out what some of the variables are. For example, what type is lstGroupInfo? or tripAddressInfo? Jan 18, 2012 at 14:11
• Thanks for analyzing the query, i have updated the code. Kindly tell me if i could help me more. Jan 19, 2012 at 4:06

There's quite a lot of logic in there, so I doubt you will get there completely by using LINQ, and, more importantly, if it would actually be more elegant.

I would rewrite as follows, and be done with it:

        foreach (AddressInfo addressInfo in subDetails)
{
if (grpInfo != null)
{
}
else
{
grpInfo = new GroupInfo();
}
}


In addition, it seems to me that Rural and Urban are mutually exclusive, so why not define an enumeration that contains those two (or more) values, or declare one boolean property IsRural to indicate if it's "Rural", and if not, it's urban. That would bring the code down to:

        foreach (AddressInfo addressInfo in subDetails)
{
if (grpInfo != null)
{
}
else
{
grpInfo = new GroupInfo();