Linq List of Objects GroupBy Multiple Property Equality
I have a List<ReportObject> and want to be able to combine certain
elements of the list into a single element based on the equality of
certain properties from one element matching certain other properties from
a second element in the list. In this case, I want to update the first
element with values from the second element and then return a list with
only the collection of "first elements".
Perhaps GroupBy (or LINQ in general) isn't the right solution here, but it
does seem like it would be a lot cleaner than doing a traditional foreach
loop and newing up a second list. What I want is something like this:
List<ReportObject> theList = new List<ReportObject>()
{ new ReportObject() { Property1 = "1",
Property2 = "2" },
new ReportObject() { Property1 = "2",
Property2 = "3" }
new ReportObject() { Property1 = "1",
Property2 = "3" } };
List<ReportObject> newList = new List<ReportObject>();
for(int i = 0; i < theList.Count; i++)
{
if (theList[i].Property1 == theList[i+1].Property2)
{
theList[i].Property2 = theList[i+1].Property2);
newList.Add(theList[i]);
theList.RemoveAt(i+1);
}
}
return newList;
No comments:
Post a Comment