Create combined Lists from multiple Lists
It looks like what you're looking for is a connected component list. I answered a similar question about this here, but this question is different enough that I think it warrants it's own answer:
var combinedCoords = new List<List<int>>();
foreach(var c in coords)
{
var merge = new List<List<int>>();
foreach(var g in combinedCoords)
{
if (c.Any(g.Contains))
{
merge.Add(g);
}
}
if (merge.Count == 0)
{
combinedCoords.Add(c);
}
merge.Add(c);
for(int i = 1; i < merge.Count; i ++)
{
foreach(var v in merge[i].Except(merge[0]))
{
merge[0].Add(v);
}
combinedCoords.Remove(merge[i]);
}
}
This produces two lists:
{ 0, 1, 2, 3, 4, 5 }
{ 7, 8, 9, 10 }
If you refactor coords
and combinedCoords
to be a List<HashSet<int>>
, the algorithm is a little simpler, and it should perform better:
var combinedCoords = new List<HashSet<int>>();
foreach(var c in coords)
{
var merge = new List<HashSet<int>>(combinedCoords.Where(c.Overlaps));
if (merge.Count == 0)
{
combinedCoords.Add(c);
}
else
{
merge[0].UnionWith(c);
for(int i = 1; i < merge.Count; i ++)
{
merge[0].UnionWith(merge[i]);
combinedCoords.Remove(merge[i]);
}
}
}