Reputation: 13636
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
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
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 Substring
s:
foreach (char c in str.Substring(0, 3)) {
...
}
Upvotes: 6