我假設你有三個類實現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