Michael
Michael

Reputation: 13636

How to retrieve characters from string with help of LINQ?

I have string:

string str = "GoodDay";

I need to retrieve the first three characters with the help of LINQ.

Any idea how to implement this?

Upvotes: 1

Views: 1400

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

String is IEnumerable<char> so you can query it. Use Enumerable.Take method:

IEnumerable<char> firstThreeChars = str.Take(3);

If it's not required for you to use LINQ, then better option is usage of str.Substring(0,3) - that will return substring containing first three characters.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

If you must use LINQ, you can do this:

foreach ( char c  in str.Take(3)) {
    ...
}

However, with strings it is much more conventional to use Substrings:

foreach (char c in str.Substring(0, 3)) {
    ...
}

Upvotes: 6

Related Questions