Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of lists

Is there a better, more elegant and concise, way to get the intersection of two lists in C#?

In C# a method to calculate an intersection of list of dates is:

    public List<DateTime> dates_common(Timeserie ts1, Timeserie ts2)
    {
        var dt1 = new HashSet<DateTime>(ts1.dates);
        var dt2 = new HashSet<DateTime>(ts2.dates);
        dt1.IntersectWith(dt2);
        var dt = new DateTime[dt1.Count];
        dt1.CopyTo(dt);
        return new List<DateTime>(dt);
    }

In Ruby one would do this as:

def dates_common(ts1, ts2)
    dt1 = ts1.dates.to_set    
    dt2 = ts2.dates.to_set
    return dt1.intersection(dt2).to_a
end

The root cause of this clunkiness is the asymmetry between IEnumerable and concrete containers and arrays.

I am constantly amazed how badly designed C# standard libraries are as this kind of problems come up all the time.

Is there a better, this means more elegant and concise, way to do this?

like image 976
IHMS Avatar asked Nov 18 '11 15:11

IHMS


1 Answers

You can use the Enumerable.Intersect and Enumerable.ToList extension methods as follows to get very elegant and concise code:

public List<DateTime> dates_common(Timeserie ts1, Timeserie ts2)
{
    return ts1.dates.Intersect(ts2.dates).ToList();
}
like image 77
dtb Avatar answered Sep 19 '22 15:09

dtb