问题
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?
回答1:
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();
}
回答2:
// This function is used to remove those alias from 'cc' which are common in 'to' and 'cc' list.
private static void RemoveCommonFromCc(ref List<string> to, ref List<string> cc)
{
IEnumerable<string> common = (List<string>)to.Intersect(cc);
foreach(var removeCc in common)
{
cc.Remove(removeCc);
}
}
来源:https://stackoverflow.com/questions/8184933/intersection-of-lists