Reputation: 1694
I'm wondering what's the most efficient (edit: fastest) way of converting IEnumerable<HashSet<T>>
to a single Hashset<T>
with all its elements.
Sample situation:
Providing:
class Rectangle
{
public HashSet<Point> PointSet { get; set; }
}
Implement efficiently:
HashSet<Point> ExtractUniquePoints(IEnumerable<Rectangle> rectangles) {}
Inefficient solution:
HashSet<Point> ExtractUniquePoints(IEnumerable<Rectangle> rectangles)
{
HashSet<Point> uniquePoints = new HashSet<Point>();
foreach (Rectangle rectangle in rectangles)
{
foreach (Point point in rectangle.PointSet)
{
uniquePoints.Add(point);
}
}
return uniquePoints;
}
Thanks in advance!
Upvotes: 0
Views: 209
Reputation: 38880
I don't think there's necessarily a faster way to do what you're doing (at least not with HashSets), but a shorter method is the following:
HashSet<Point> ExtractUniquePoints(IEnumerable<Rectangle> rectangles)
{
return new HashSet<Point>(rectangles.SelectMany(r => r.PointSet));
}
Or if you're using .NET Core, simply:
HashSet<Point> ExtractUniquePoints(IEnumerable<Rectangle> rectangles)
{
return rectangles.SelectMany(r => r.PointSet).ToHashSet();
}
Upvotes: 2