Zé Carlos
Zé Carlos

Reputation: 3807

Use Func<> type to assign/change variables

I already know that the following 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.

Upvotes: 1

Views: 143

Answers (4)

Amy B
Amy B

Reputation: 110221

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.

Upvotes: 0

dbkk
dbkk

Reputation: 12852

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);

Upvotes: 1

ba__friend
ba__friend

Reputation: 5913

Or even easier, if you are only working with strings.

var s = string.Join(string.Empty, someEnumerable)

Upvotes: 2

George Duckett
George Duckett

Reputation: 32468

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.

Upvotes: 7

Related Questions