Вот забавный, который я собрал. Пожалуйста, имейте в виду, что это не очень эффективно, особенно для простых замен. Тем не менее, было весело писать и поддается довольно читабельной модели использования. Это также подчеркивает малоизвестный факт, что String реализует IEnumerable.
public static class LinqToStrings
{
public static IQueryable<char> LinqReplace(this string source, int startIndex, int length, string replacement)
{
var querySource = source.AsQueryable();
return querySource.LinqReplace(startIndex, length, replacement);
}
public static IQueryable<char> LinqReplace(this IQueryable<char> source, int startIndex, int length, string replacement)
{
var querySource = source.AsQueryable();
return querySource.Take(startIndex).Concat(replacement).Concat(querySource.Skip(startIndex + length));
}
public static string AsString(this IQueryable<char> source)
{
return new string(source.ToArray());
}
}
А вот пример использования:
public void test()
{
var test = "test";
Console.WriteLine("Old: " + test);
Console.WriteLine("New: " + test.LinqReplace(0, 4, "SOMEPIG")
.LinqReplace(4, 0, "terrific")
.AsString());
}
Выходы:
Old: test
New: SOMEterrificPIG
Другая версия того же подхода, которая не так ужасно медленная, проста с использованием подстроки:
public static string ReplaceAt(this string source, int startIndex, int length, string replacement)
{
return source.Substring(0, startIndex) + replacement + source.Substring(startIndex + length);
}
И в замечательном примере того, почему вы должны профилировать свой код, и почему вы, вероятно, должны не использовать мою реализацию LinqToStrings в рабочем коде, вот тест синхронизации:
Console.WriteLine("Using LinqToStrings: " + new Stopwatch().Time(() => "test".LinqReplace(0, 4, "SOMEPIG").LinqReplace(4, 0, "terrific").AsString(), 1000));
Console.WriteLine("Using Substrings: " + new Stopwatch().Time(() => "test".ReplaceAt(0, 4, "SOMEPIG").ReplaceAt(4, 0, "terrific"), 1000));
Который измеряет такты таймера в 1000 итераций, производя такой вывод:
Using LinqToStrings: 3,818,953
Using Substrings: 1,157