是否有更好,更优雅和简洁的方法来获取C#中两个列表的交集?
Is there a better, more elegant and concise, way to get the intersection of two lists in C#?
在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); }在Ruby中,这样做是:
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这种笨拙的根本原因是IEnumerable与具体容器和数组之间的不对称性.
The root cause of this clunkiness is the asymmetry between IEnumerable and concrete containers and arrays.
我一直惊讶于C#标准库的设计多么糟糕,因为这种问题一直在出现.
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?
推荐答案您可以使用 Enumerable.Intersect 和 Enumerable.ToList 扩展方法,如下所示,可以获得非常简洁明了的代码:
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(); }更多推荐
列表的交集
发布评论