我假设你有三个类实现IRule(AddRule,EditRule,DeleteRule)。
如果您可以将IList的allRules类型更改为List,则可以使用List<T>.Sort(Comparison<T>)
方法。 Comparison是一个通用的委托与签名
public delegate int Comparison<in T>(T x,T y)
所以你需要的东西是这样的:
public int IRuleComparer(IRule first, IRule second)
{
//build a table of type weights (this could be made static)
Dictionary<Type, int> typeWeights = new Dictionary<Type, int>();
typeWeights.Add(typeof(AddRule), 1);
typeWeights.Add(typeof(EditRule), 2);
typeWeights.Add(typeof(DeleteRule), 3);
//get the types of the arguments
Type firstType = first.GetType();
Type secondType = second.GetType();
//are the types valid?
if (!typeWeights.ContainsKey(firstType))
throw new Exception("invalid first type");
if (!typeWeights.ContainsKey(secondType))
throw new Exception("invalid second type");
//compare the weights of the types
return typeWeights[firstType].CompareTo(typeWeights[secondType]);
}
另外,还要注意的是,排序实现使用快速排序算法,这不是一个稳定排序,即它可能会混淆AddRules的相对顺序,所以在您的示例中,AddRule2可能会在AddRule1之前排序。
或者,你可以使用LINQ像这样的东西:
public int GetRuleWeight(IRule item)
{
//build a table of type weights (this could be made static)
Dictionary<Type, int> typeWeights = new Dictionary<Type, int>();
typeWeights.Add(typeof(AddRule), 1);
typeWeights.Add(typeof(EditRule), 2);
typeWeights.Add(typeof(DeleteRule), 3);
Type itemType = item.GetType();
if (!typeWeights.ContainsKey(itemType))
throw new Exception("invalid type");
return typeWeights[itemType];
}
allRules = allRules.OrderBy(item => GetRuleWeight(item)).ToList();
这将IList的(甚至IEnumerable的),所以你不会有改变allRules的类型。
你已提供的IComparer到allRules.Sort()方法或代替对比逻辑使用LambdaComparer与 –
sll
是否要保留每个类别中的现有订单? (也就是说,你是否想要'A1 A2 E1 D1 D2 D3',或者'A2 A1 E1 D2 D2 D3 D1'确定)。 – AakashM
'List'ha a Sort method。 'IList '不(因此问题不同)。在示例中使用'List',在标题中使用'IList'。 –
xanatos