I have a List of objects with this implementation:
class Locations
{
public string Origin { get; set; }
public string Dest { get; set; }
public int Total { get; set; }
}
I need to output a table, in CSV format, that has the Origins as rows, the Destinations as columns, and the Total where the specified Origins and Destinations meet. There could be an arbitrary number of Location objects in my List.
Given the following records in my List:
Origin=A
Dest=B
Total=10
Origin=B
Dest=A
Total=20
My output would look like this (with the ‘-‘ character meaning there’s no Total between identical Origin/Destinations):
Origins/Destinations,A,B
A,-,10
B,20,-
Thus far, I have done the following:
1) Traverse the List to output the Destinations.
2) Traverse the List to output an Origin. For the Origin, traverse the list to find the Total for each Destination related to the Origin.
3) Repeat #2 for the next Origin.
My results aren’t quite working out as the row/column data doesn’t always match up. Is there a simpler solution to this?
Update
After reading your update it seems that there’s no need to sum as there is only going to be one object with a given
OriginandDestination. In that case you can keep the code that collectsplaces, do the nestedforeachand simply get the total withOriginal answer
You can get a list of all locations with
At this point you can simply iterate over
placesfor the rows and do another nested iteration for the columns:You can immediately see how you can easily construct a table with this structure. The main disadvantage of this approach is that it’s doing a lot more work than strictly necessary; theoretically we can certainly iterate just once over
locations, collecting the information as we go. It’s possible to sum up theTotalfor each pair ofOriginandDestwithAt this point we can take a page from the first solution: