Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<string> to string

Tags:

c#

linq

Consider this:

string test = "";
somestring.ToList().Take(50).Select(
    delegate(char x)
    {
        test += x;
        return x;
    }
);

Why is test empty after that? I don't care about the return of that actually (I know its IEnumerable<string>).

If this is all seems a mess then how can I convert the IEnumerable<char> returned by Select() to string ?

like image 313
Stacker Avatar asked Sep 23 '10 11:09

Stacker


People also ask

What is IEnumerable string in c#?

IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.

What is IEnumerable<>?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

Why we use IEnumerable in web api?

IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.


2 Answers

Because you didn't execute the query. Linq is lazy. It will be executed when you do either foreach or ToList/ToArray/ToDictionary.

and i advice to do it like that

string test = new string(somestring.Take(50).ToArray());

or even using

string test = somestring.Substring(0, 50);

More on that. Select is intended to apply some kind of transformation to every element in sequence. This operation is also known as map. If you want to produce single element from sequence it is Aggregate, aka reduce. It is not lazy, it forces execution of query.

like image 154
Andrey Avatar answered Sep 24 '22 21:09

Andrey


(Others have explained why it doesn't work.)

Your question doesn't quite make sense at the moment - it's not clear whether you're actually dealing with an IEnumerable<char> or an IEnumerable<string>. (Your text suggests IEnumerable<string>; your code suggests IEnumerable<char>). If it's an IEnumerable<string> and you're using .NET 4, it's really easy:

string combined = string.Join("", list.Take(50));

If you're using .NET 3.5, it's still pretty easy:

string combined = string.Join("", list.Take(50).ToArray());

Obviously use something like "," if you want a delimiter between the strings.

If you're dealing with a general IEnumerable<char> then use

string combined = new string(chars.Take(50).ToArray());

If you're actually dealing with a string to start with, use Substring :)

like image 39
Jon Skeet Avatar answered Sep 24 '22 21:09

Jon Skeet