Use Func<> type to assign/change variables
I already know that the fo开发者_JAVA百科llowing code doesn't work
string s = "";
someEnumerable.Select(x => s+= x);
What I want to know is if there's some other way (preferably using linq) of get the above behavior without using cyclic statements such as "for" or "foreach".
Thanks.
string s = someIEnumerable.Aggregate((acc, next) => acc + next);
The acc, is the accumulator (what we've aggrigated/combined so far), next is the next element enumerated over. So, here i take what we've got so far (initially an empty string), and return the string with the next element appended.
Or even easier, if you are only working with strings.
var s = string.Join(string.Empty, someEnumerable)
Either use Aggregate
or write your own ForEach extension method:
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach (T item in enumeration) { action(item); }
}
and then do
someEnumerable.ForEach(x => s += x);
Literal answer:
string s = "";
Func<string, string> myFunc = x =>
{
s += x;
return x;
};
IEnumerable<string> query = source.Select(myFunc); //note, deferred - s not yet modified.
精彩评论