Skip to content

Instantly share code, notes, and snippets.

@mstewio
Last active May 9, 2017 15:17
Show Gist options
  • Save mstewio/36a1fba26020f7aca629a87a9b112757 to your computer and use it in GitHub Desktop.
Save mstewio/36a1fba26020f7aca629a87a9b112757 to your computer and use it in GitHub Desktop.
This code snippet flattens multiple lists within a list, joins the resulting list to a related list where the two share an ID, and lastly, creates a comma delimited string by joining a list of strings.
/// <summary>
/// Using https://msdn.microsoft.com/en-us/library/bb534336(v=vs.110).aspx as a guide,
/// here's how I flattend out a list within a list.
/// </summary>
public class ListWithinList
{
public static void Main(string[] args)
{
var widgets = new List<Widget>
{
new Widget { WidgetID = 1 },
new Widget { WidgetID = 2 },
};
var factories = new List<Factory>
{
new Factory
{
Parts = new List<Part>
{
new Part { PartID = 1, PartDescription = "Hammer" },
new Part { PartID = 1, PartDescription = "Screwdriver" },
new Part { PartID = 1, PartDescription = "Sharpener" },
new Part { PartID = 2, PartDescription = "Saw" },
new Part { PartID = 2, PartDescription = "Rake" },
}
}
};
// Flatten
IEnumerable<Part> parts = factories.SelectMany(f => f.Parts);
// With a little help from John Skeet
// http://stackoverflow.com/questions/7325278/group-by-in-linq
IEnumerable<Widget> updatedWidgets = from widget in widgets
join part in parts on widget.WidgetID equals part.PartID
group part.PartDescription by part.PartID into partsGrouping
select new Widget
{
WidgetID = partsGrouping.Key,
WidgetDescription = string.Join(", ", partsGrouping.ToList())
};
// Outputs
// [0]{ WidgetID = 1, Description = "Hammer, Screwdriver, Sharpener" }
// [1]{ WidgetID = 2, Description = "Saw, Rake" }
}
}
public class Widget
{
public int WidgetID { get; set; }
public string WidgetDescription { get; set; }
}
public class Factory
{
public List<Part> Parts { get; set; }
}
public class Part
{
public int PartID { get; set; }
public string PartDescription { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment