Invoking HashSet.Add(item) in Linq vs foreach loop
c#, linq
Solution
You `Select` it, but don't do anything with the result. Because of LINQ's lazy evaluation (it generates the results on-demand through an `IEnumerable`) it just won't get executed. Use the `foreach` loop, it's the cleanest possible solution.
(The other solution is to use a `List<Customer>` instead and call `ForEach` on that... but unless you have a really good reason for wanting to use a method with a callback, there's no advantage.)
Edit: Actually, if all you're doing is adding elements to the `HashSet`, the cleanest possible solution is `UnionWith`:
customers.UnionWith(innerCustomers);
Problem
Need help in following code segment: ``` static void Main(string[] args) { var customers = new HashSet<Customer>(); var action = new Action(() => { var innerCustomers = new Customer[] { new Customer { CustomerID = 1, CustomerName = "C 1" }, new Customer { CustomerID = 2, CustomerName = "C 2" }, }; innerCustomers.Select(c => customers.Add(c)); //doesn't work foreach (var customer in innerCustomers) customers.Add(customer); //works fine }); action(); } ``` `innerCustomers.Select(c => customers.Add(c));` does not seem to be working in terms of inserting records in the "customers" collection however, "foreach" down below that line works fine. Anybody has any idea why it's not working in linq? I know i am not selecting anything out of the select method