这行得通:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main( string[] args )
{
var intList = new List<int> { 1000, 9102, 123, 41, 10, 52, 24, 8, 26 };
intList.ToArray()
.Sort( 0, 100, x => x > 27 );
}
}
public static class Ex
{
public static void Sort<T>( this T[] input, int low, int high, Func<T, bool> predicate )
{
input.ToList()
.ForEach( x => predicate( x ) );
}
}
}
编辑:
这是有效的,因为定义的谓词“谓词”表示一个以 T 的对象作为参数并返回布尔值的函数。而我所做的只是创建一个与定义的谓词匹配的匿名函数……
我无法解释为什么或什么在 Schalks 代码中不起作用,因为我不知道他的代码……
编辑 2(添加完整的代码示例):
如果您使用 List 的 Sort(int index, int count, IComparer comparer) 方法,则需要一个 IComparer 实例来比较列表项。如果您希望能够将比较器指定为 lambda 表达式,则需要一个实现 IComparer 的类,该类在内部使用 lambda 表达式来比较项目。 (或者使用 .net 4.5 你可以使用Comparer<T>.Create Method 。)
这是一个完整的示例:
public class Program
{
public static void Main( string[] args )
{
var idiots = new List<Idiot>
{
new Idiot { Weapons = new[] { new Weapon { Damage = 10 }, new Weapon { Damage = 20 } } },
new Idiot { Weapons = new[] { new Weapon { Damage = 6 }, new Weapon { Damage = 100 } } },
new Idiot { Weapons = new[] { new Weapon { Damage = 45 }, new Weapon { Damage = 12 } } },
new Idiot { Weapons = new[] { new Weapon { Damage = 24 }, new Weapon { Damage = 5 } } },
};
foreach ( var i in idiots )
i.Weapons.QuickSort( 0, i.Weapons.Count() - 1, ( a, b ) => a.Damage.CompareTo( b.Damage ) );
//Solution using IEnumerable{T} extension methods
idiots.ForEach( x => x.Weapons = x.Weapons.OrderBy( y => y.Damage ).ToArray() );
}
}
public static class Ex
{
public static void QuickSort<T>(this IEnumerable<T> input, int low, int high, Func<T, T, Int32> comparer)
{
input
.ToList()
.Sort( low, high, new FunctionalComparer<T>( comparer ) );
}
}
public class FunctionalComparer<T> : IComparer<T>
{
private readonly Func<T, T, Int32> comparer;
public FunctionalComparer(Func<T, T, Int32> comparer)
{
this.comparer = comparer;
}
public Int32 Compare(T x, T y)
{
return comparer( x, y );
}
public static IComparer<T> Create(Func<T, T, Int32> comparer)
{
return new FunctionalComparer<T>( comparer );
}
}
public class Idiot
{
public Weapon[] Weapons { get; set; }
}
public class Weapon
{
public Int32 Damage { get; set; }
}
FunctionalComparer 实现 IComparer 并根据给定的 lambda 表达式比较两个对象。
QuickSort 创建一个 FunctionalComparer 实例(使用给定的表达式)并使用该实例对项目进行排序。
但您可以使用 IEnumerable 扩展方法来执行此操作,而不是编写所有这些代码。