I have a collection like this:
IEnumerable<Query> queries;
I am searching for the ones contained in keys of a dictionary and I want to do something on matching value.I know this is possible:
(from query in queries
where _metadata.ContainsKey(query.Value)
select query).ToList().ForEach(result=>_metadata[result.Value].AddQuery(result));
I wonder if I could make it simpler by calling AddQuery() in matching query enumerations. Query is immutable, so it should not break it.It should be something like this.
from query in queries
where _metadata.ContainsKey(query.Value)
//do something like _metadata[query.Value].AddQuery(query)
Why not just do:
You can provide lambdas to Select, Where etc which have side-effects – but it’s generally a bad idea; LINQ queries are meant to be stateless, ideally – you should be able to iterate over the query multiple times with no problems. Here, we’ve clearly separated the side-effect (adding a query to
_metadata) from the query.Note that the above code still works slightly differently to your original though, due to the way
Whereis executed – each new query will be added before the remainingWherepredicates are executed. In other words, although your query itself is side-effect free, the side-effect you’re introducing has an impact on the query.