列表的交集

编程入门 行业动态 更新时间:2024-10-15 00:27:34
本文介绍了列表的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有更好,更优雅和简洁的方法来获取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(); }

更多推荐

列表的交集

本文发布于:2023-11-29 12:24:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!