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
You
Selectit, but don’t do anything with the result. Because of LINQ’s lazy evaluation (it generates the results on-demand through anIEnumerable) it just won’t get executed. Use theforeachloop, it’s the cleanest possible solution.(The other solution is to use a
List<Customer>instead and callForEachon 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 isUnionWith: