Performing an operation during enumeration
I have a collection like this:
IEnumerable<开发者_如何学CQuery> 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:
foreach (var query = queries.Where(q => _metadata.ContainsKey(query.Value)))
{
_metadata[query.Value].AddQuery(query)
}
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 Where
is executed - each new query will be added before the remaining Where
predicates 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.
You can use something like this, pseudocode:
queries.ForEach(query=> {
if(_metadata.ContainsKey(query.Value))
//do somethign ...
});
Hope this helps.
EDIT
If this is not list, consider @Jon's solution => just foreach
loop
精彩评论