I have an ArrayList ids
containing String
objects that are IDs, and another ArrayList objs
containing objects which have a string ID field. Right now I have code, to find which ids
don't have a match in objs
, which looks like this:
var missing = new List<string>();
foreach (MyObj obj in objs)
{
if (!ids.Contains(obj.ID))
{
missing.Add(obj.ID);
}
}
This works fine. But I rewrote it to this an exercise to better "think in LINQ":
var missing = objs.Cast<MyObj>().Select(x => x.ID).Except(ids.Cast<string>());
I expected this LINQ to be slower than the foreach
+ Contains
approach (especially due to the Cast
calls), but the LINQ runs significantly faster. What is the LINQ approach doing differently that gives the performance benefit?