假设您有字符串项目,并且您希望按其他列表优先级对它们进行优先级排序。
这是我的示例,其中我有优先级列表,这些优先级将按优先级排列在排序列表中。
结果
kitty , some item , kk abb , ccc , kk abc, some flash
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var input = new List<string>()
{
"some item",
"some flash",
"kitty",
"ccc",
"kk abc",
"kk abb"
};
var sorted = input.OrderBy(x => x, new Comparer()).ToList();
Console.ReadKey();
}
}
public class Comparer : IComparer<string>
{
private List<KeyValuePair<string, int>> priorities = new List<KeyValuePair<string, int>>()
{
new KeyValuePair<string, int>("some item", 2),
new KeyValuePair<string, int>("kitty", 1),
new KeyValuePair<string, int>("kk abb", 3),
};
public int Compare(string x, string y)
{
var anyX = priorities.Any(z => z.Key == x);
var anyY = priorities.Any(z => z.Key == y);
if (anyX || anyY)
{
var firstX = priorities.FirstOrDefault(z => z.Key == x);
var firstY = priorities.FirstOrDefault(z => z.Key == y);
if (anyX && anyY)
{
if (firstX.Value > firstY.Value)
{
return firstX.Value;
}
return -firstX.Value;
}
if (anyX)
{
return -firstX.Value;
}
if (anyY)
{
return firstY.Value;
}
}
return string.Compare(x, y, StringComparison.Ordinal);
}
}