I'm working on a Xamarin application and I'm presenting a list of objects in a TableView that are grouped by a specific property of the object.
The property is a date. For each distinct date, I am creating a table section with a header containing said date. Below is the working code to accomplish this, but It's not very elegant.
var trades = new List<ViewCell>();
Dictionary<string, List<ViewCell>> dict = new Dictionary<string, List<ViewCell>>();
// organizing each object into a dictionary with a key that
// represents the table header and value for the sections objects
foreach (var item in completed)
{
var date = item.DateClosed.ToString("MMMM dd yyyy");
if (dict.ContainsKey(date))
{
dict[date].Add(new TradeCell(item));
}
else {
dict[date] = new List<ViewCell> { new TradeCell(item) };
}
}
// looping through the resulting dict to assemble the table
foreach (KeyValuePair<string, List<ViewCell>> entry in dict)
_table.Root.Add(new TableSection(entry.Key) { entry.Value });
My Question
This gets the job done but I was hoping for a more elegant approach, perhaps using linq?
GroupBy
to do what you want. \$\endgroup\$