[英]Intersection of lists
有沒有更好、更優雅、更簡潔的方法來獲得 C# 中兩個列表的交集?
在 C# 中,計算日期列表交集的方法是:
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 中,人們會這樣做:
def dates_common(ts1, ts2)
dt1 = ts1.dates.to_set
dt2 = ts2.dates.to_set
return dt1.intersection(dt2).to_a
end
這種笨拙的根本原因是 IEnumerable 與具體容器和數組之間的不對稱。
我一直驚訝於 C# 標准庫的設計有多糟糕,因為這種問題一直出現。
有沒有更好的,這意味着更優雅和簡潔的方法來做到這一點?
您可以使用Enumerable.Intersect和Enumerable.ToList擴展方法如下,以獲得非常優雅和簡潔的代碼:
public List<DateTime> dates_common(Timeserie ts1, Timeserie ts2)
{
return ts1.dates.Intersect(ts2.dates).ToList();
}
// 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.