Generating Table Sections from A Property in a List of Objects 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&lt;ViewCell&gt;();
    Dictionary&lt;string, List&lt;ViewCell&gt;&gt; dict = new Dictionary&lt;string, List&lt;ViewCell&gt;&gt;();

    // 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&lt;ViewCell&gt; { new TradeCell(item) };
        } 
    }

    // looping through the resulting dict to assemble the table             
    foreach (KeyValuePair&lt;string, List&lt;ViewCell&gt;&gt; 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?
You asked for a more elegant approach... This is certainly more concise:

var dict = completed
    .GroupBy(
        item =&gt; item.DateClosed.ToString("MMMM dd yyyy"), // Key selector
        item =&gt; new TradeCell(item)) // Value selector
    .ToDictionary(g =&gt; g.Key, g =&gt; g.ToList());


However, you don't actually need the dictionary (that's just to keep the same behaviour as the foreach). This should do the job:

foreach (var groupOfCells in completed.GroupBy(item =&gt; item.DateClosed.ToString("MMMM dd yyyy"), item =&gt; new TradeCell(item)))
{
    _table.Root.Add(new TableSection(groupOfCells.Key) { groupOfCells .ToList() });
}


Remember not to abbreviate names. dict doesn't mean anything to anyone.

I'd also suggest grouping by DateClosed.Date and converting to a string in your UI layer. I don't know if you need it, but it's much harder to localise if you include hard coded format strings all over the place.