2016-12-15 73 views
-2

我需要在我的项目中实现特定的排序机制。如何实现特定的排序?

上下文:最终用户希望在可用时首先看到一些项目。

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

你可以试试这个

var result = myTotalColllection 
    .OrderBy(x => Array.IndexOf(myPreferedOrder, x)<0?int.MaxValue: Array.IndexOf(myPreferedOrder, x)) 
    .ToArray(); 
+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; 
} 
+0

现在,它的工作原理!谢谢! –