Reputation: 20464
How I could fix this LINQ extension? (in C# or VB no matter):
States.Select(Function(item) myMethod(item.Key, item.Value))
States
object is a Dictionary, and what I'm trying to reproduce using LINQ is the same as this:
For each item in states
myMethod(item.Key, item.Value)
Next item
I know that I'm missing something because the Select extension in that way is not the solution... but, I don't know.
Upvotes: 0
Views: 147
Reputation: 152541
Linq is for querying - it is designed to iterate over a collection and return a result for each item. There are ForEach
extension methods out there that just wrap foreach
, but in my opinion (and others') they are pointless because they only change the syntax, they do not improve it.
You could fake it out in C# by returning a dummy value:
States.Select(item => {myMethod(item.Key, item.Value); return 0;})
or in VB:
States.Select(Function(item)
myMethod(item.Key, item.Value)
Return 1
End Function)
but I think that just adds confusing noise - a foreach
is definitely more appropriate.
Upvotes: 1
Reputation: 13381
I think you mean ForEach extension, you may use it like this
States.ToList().ForEach(Function(item) myMethod(item.Key, item.Value))
Upvotes: 2
Reputation: 70523
From your example there is no no way to "reproduce" this in linq. The function does not return a value. If myMethod() returned something you could create a list of all the results like this (C#)
var resultlist = States.Select(item => myMethod(item.Key,item.Value));
But there is no reason to use linq if the method does not return a value -- just use the for each like you had originally.
Upvotes: 1