2 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用Skip并Take實(shí)現(xiàn)它。
var input = new[] { "a", "b", "c", "d", "e" };
var res = input.Take(1)
.Concat(input.Skip(1).Take(3).OrderByDescending(e => e))
.Concat(input.Skip(4));
你也可以像這樣做一個(gè)擴(kuò)展方法
public static class IEnumerableExt
{
public static IEnumerable<TSource> OrderRangeByDescending<TSource, TKey>(this IEnumerable<TSource> input, Func<TSource, TKey> keySelector, int from, int length)
{
return input.Take(from)
.Concat(input.Skip(from).Take(length).OrderByDescending(keySelector))
.Concat(input.Skip(from + length));
}
public static IEnumerable<TSource> OrderRangeBy<TSource, TKey>(this IEnumerable<TSource> input, Func<TSource, TKey> keySelector, int from, int length)
{
return input.Take(from)
.Concat(input.Skip(from).Take(length).OrderBy(keySelector))
.Concat(input.Skip(from + length));
}
}
var input = new[] { "a", "b", "c", "d", "e" };
var res = input.OrderRangeByDescending(e => e, 1, 3);

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超11個(gè)贊
重復(fù)調(diào)用Skip和Take可能會(huì)對(duì)性能產(chǎn)生影響,特別是如果源是由密集計(jì)算生成的。最佳解決方案將要求對(duì)源的讀取僅發(fā)生一次。這可以通過將源拆分為多個(gè)枚舉但使用單個(gè)枚舉器來實(shí)現(xiàn)。擁有這樣一個(gè) Splitter 將使我們能夠很容易地實(shí)現(xiàn)OrderRangeBy/OrderRangeByDescending方法:
public static IEnumerable<TSource> OrderRangeBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
int startIndex, int endIndexExclusive)
{
var parts = source.Split(startIndex, endIndexExclusive);
return parts[0].Concat(parts[1].OrderBy(keySelector)).Concat(parts[2]);
}
public static IEnumerable<TSource> OrderRangeByDescending<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
int startIndex, int endIndexExclusive)
{
var parts = source.Split(startIndex, endIndexExclusive);
return parts[0].Concat(parts[1].OrderByDescending(keySelector)).Concat(parts[2]);
}
下面是 Splitter 的一個(gè)實(shí)現(xiàn):
public static IEnumerable<TSource>[] Split<TSource>(
this IEnumerable<TSource> source, params int[] indices)
{
var parts = new IEnumerable<TSource>[indices.Length + 1];
var enumerator = source.GetEnumerator();
int index = 0;
for (int i = 0; i < indices.Length; i++)
{
parts[i] = GetPart(indices[i]);
}
parts[indices.Length] = GetPart(Int32.MaxValue);
return parts;
IEnumerable<TSource> GetPart(int maxIndexExclusive)
{
if (index >= maxIndexExclusive) goto finish;
while (enumerator.MoveNext())
{
yield return enumerator.Current;
index++;
if (index >= maxIndexExclusive) break;
}
finish: if (maxIndexExclusive == Int32.MaxValue) enumerator.Dispose();
}
}
- 2 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)