eduherminio
eduherminio

Reputation: 1694

Efficient conversion of HashSet list to a single HashSet

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

Answers (1)

ProgrammingLlama
ProgrammingLlama

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

Related Questions