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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With