GetEnumerator () in the middle of the line

Suppose I have a very long string and you want to get an enumerator (for LINQ goodness) that starts in the middle of the string at the given index. I.e

var longString = GetLongString();
var index = 99999;

// seems unnecessarily expensive to allocate a new string
var enumerator = longString.Substring(9999).GetEnumerator();

// Use LINQ.
enumerator.TakeWhile( /* ... */ );

is there a better way (i.e.: cheaper / faster)?

+4
source share
2 answers

Consider Enumerable.Skip:

longString.Skip(9999).TakeWhile( /* ... */ );

However, keep in mind that, as Michael Liu wrote , Skipiteratively works (strictly speaking, it depends on the implementation, but at least this is what you usually have, for example, the .NET Framework 4.6 Link Sources ). If this leads to measurable slowness 1 in your case, look at Michael's extension method.


+9

longString.Skip(n), AlexD answer, n MoveNext, , . n , :

public static IEnumerable<char> EnumerableSubstring(this string s, int startIndex)
{
    for (; startIndex < s.Length; startIndex++)
        yield return s[startIndex];
}

:

longString.EnumerableSubstring(9999).TakeWhile( /* ... */ )
+5

Source: https://habr.com/ru/post/1599600/


All Articles