1250.md

February 3, 2022 ยท View on GitHub

Consider the following code snippet

public IEnumerable<GoldMember> GetGoldMemberCustomers()
{
	const decimal GoldMemberThresholdInEuro = 1_000_000;

	var query =
		from customer in db.Customers
		where customer.Balance > GoldMemberThresholdInEuro
		select new GoldMember(customer.Name, customer.Balance);

	return query;
}

Since LINQ queries use deferred execution, returning query will actually return the expression tree representing the above query. Each time the caller evaluates this result using a foreach loop or similar, the entire query is re-executed resulting in new instances of GoldMember every time. Consequently, you cannot use the == operator to compare multiple GoldMember instances. Instead, always explicitly evaluate the result of a LINQ query using ToList(), ToArray() or similar methods.