我有一个复杂的排序方法:
/// <summary>
/// Performs an advanced sort on products using sortations
/// </summary>
/// <param name="products">The products to sort</param>
/// <param name="sortations">The sortation list</param>
public void AdvancedSort(List<JObject> products, List<Sortation> sortations)
{
// Throw if we don't have our injected handler
ThrowIf.ArgumentIsNull(() => _expressionHandler);
// Get our value types
GetTypesFromOperator(sortations);
// Replace our variable expressions
_expressionHandler.ReplaceVariables(sortations, products);
// For each sortation
foreach (var sortation in sortations)
{
// Sort our products by the sortations
products.Sort((a, b) =>
{
// Get our values
var fieldName = sortation.Field;
var x = a.SelectToken(fieldName).ToString().Trim();
var y = b.SelectToken(fieldName).ToString().Trim();
var type = sortation.Type;
// If both values are the same, skip the rest of this iteration
if (x.Equals(y)) return 0;
// If we have an expression
if (!string.IsNullOrEmpty(sortation.Expression))
{
// If we are checking for between
if (sortation.Operator == "><")
{
// Get our values
var values = sortation.Expression.Split(',');
// If we have 2 values
if (values.Length == 2)
return CompareBetween(values, x, y);
}
// If we are checking booleans
if (sortation.Operator == "===")
return CompareBoolean(sortation.Expression);
// If we are checking equals
if (sortation.Operator == "=")
return y.Equals(sortation.Expression) ? 1 : -1;
// If we are checking like
if (sortation.Operator == "%")
return y.Equals(sortation.Expression, StringComparison.OrdinalIgnoreCase) ? 1 : -1;
}
// If we get this far, do a switch on sortation types
switch (sortation.Type)
{
case SortationValueType.Boolean:
return Boolean.Parse(x) ? -1 : 1;
case SortationValueType.Number:
return CompareNumeric(x, y, sortation.Direction);
default:
return string.CompareOrdinal(x, y);
}
});
}
}
我认为它工作正常,但这一行:
if (x.Equals(y)) return 0;
重新订购我的商品,即使它们是相同的。事实证明这是设计原因,因为 Sort 方法不稳定。 我想稳定我的排序方法,我无法将我的方法转换为linq OrderBy 因为我的排序方法过于复杂。
有谁知道如何稳定排序方法?