Intersect two List<> in C#

非 Y 不嫁゛ 提交于 2020-01-23 18:47:47

问题


I have two List<T> objects that I would like to intersect, but I get errors when trying.

// Make the Keys in the Dictionary<Load, double> _loads to form a List<Load>
List<Load> l1 = _loads.Keys.ToList();

// Get a list from my element.
List<Load> l2 = element.ListLoads;

// Intersect
List<Load> loads = (List<Load>)l1.Intersect<Load>(l2);

回答1:


Intersect<T> returns an IEnumerable<T>, so the correct way is:

var loads = l1.Intersect(l2).ToList();

ToList<T> creates a List<T> from an IEnumerable<T>.

Note that you can omit the type argument when invoking Intersect<T>, the compiler is smart enough to infer it.




回答2:


You can do it this way:

List<Load> loads=new List<Load>(l1.Intersect(l2));

This is because Intersect will return an IEnumerable and this is the right way to create a new list from an IEnumerable.



来源:https://stackoverflow.com/questions/11383329/intersect-two-list-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!