I have a List<String> and two List<CustomObject>.
I want to combine two List<CustomObject> but only if second List<CustomObject> property is not contained in List<String>.
So, want to do something like this:
resultSet1.AddRange(resultSet2.Select(x => !names.Contains(x.City)).ToList());
What am I missing here?
You are misusing
Selectwhen you should be usingWhere.Selectis a projection method. It takes a sequence and selects it, sometimes selecting the entire item, a single property, or projecting it into something else entirely.Whereis a filtering method. It takes a sequence and applies a predicate to it, yielding only the elements that pass the predicate.(In your example, by using
Select, you’re effectively trying to add a list ofboolto a list ofCustomObject, which is not going to work.)Not addressing the specific error at hand, here are some additional ideas to consider.
This is a situation where a
HashSet<string>might be beneficial fornames, particularly ifnamesis significantly large.Containson aHashSet<T>is of O(1) complexity, whereas it is O(n) forList<T>. However, there is overhead associated with the HashSet, so if you have any concerns, it’s best to measure both and see which is more performant.One more thing that might help, if you simply need to stream one sequence after the other and do not necessarily need to change or add to either collection, you might consider using
UnionorConcatoperations.The difference in the two being that
Unionwill filter out any duplicates in the resulting sequence (from both inputs, not just the second against the first),Concatapplies no duplicate-filtering logic and simply streams one sequence after the other. The input sequences (resultSet1andresultSet2) are unmodified.