问题
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