我需要在我的项目中实现一个特定的排序机制。
上下文:最终用户希望在可用时首先看到一些项目。
private List<string> SpecialSort(string[] all, string[] pref)
{
//I want to return my total collection: sorted like specified in my prefered order.
return all.ToList(); // But now in the correct order!
}
[TestMethod]
public void TestSpecialSort()
{
//Arrange
var myTotalColllection = new[] { "foo", "bar", "baz", "qux", "corge", "waldo", "thud" };
var myPreferedOrder = new[] { "waldo", "absint", "foo", "baz" };
//Act
var result = SpecialSort(myTotalColllection, myPreferedOrder);
//Assert
var expectedResult = (new[] { "waldo", "foo", "baz", "bar", "qux", "corge", "thud" }).ToList();
Assert.IsTrue(result.SequenceEqual(expectedResult));
}
我不知道.NET框架中存在这种排序功能,如果确实存在请赐教。
答案 0 :(得分:1)
向后迭代myPreferedOrder
,将all
中找到的每一个移到第一位。
private List<string> SpecialSort(string[] all, string[] pref)
{
List<string> listed = all.ToList();
foreach (string s in pref.Reverse())
if (listed.Contains(s))
{
listed.Remove(s);
listed.Insert(0, s);
}
return listed;
}
答案 1 :(得分:1)
你可以试试这个
var result = myTotalColllection
.OrderBy(x => Array.IndexOf(myPreferedOrder, x)<0?int.MaxValue: Array.IndexOf(myPreferedOrder, x))
.ToArray();