OrderBy IndexOf另一个列表

时间:2017-03-15 18:47:48

标签: c#

我觉得这很简单,但我似乎无法弄明白。

如果我有这个:

public class Program
{
    public static void Main()
    {
        TestClass test1 = new TestClass(){ID = 1, text = "STRING ONE"};
        TestClass test2 = new TestClass(){ID = 2, text = "STRING TWO"};
        TestClass test3 = new TestClass(){ID = 3, text = "STRING THREE"};
        TestClass test4 = new TestClass(){ID = 4, text = "STRING FOUR"};

        List<TestClass> lstTestClasses = new List<TestClass>();
        lstTestClasses.Add(test1);
        lstTestClasses.Add(test2);
        lstTestClasses.Add(test3);
        lstTestClasses.Add(test4);

        List<string> lstCategories = new List<string>() { "STRING TWO", "STRING ONE", "STRING THREE"};

        var orderStrings = lstTestClasses.OrderBy(x => lstCategories.IndexOf(x.text)).ToList();

        foreach(var item in orderStrings)
        {
            Console.WriteLine(item.text);
        }

        // Output:
            STRING FOUR
            STRING TWO
            STRING ONE
            STRING THREE
    }
}

public class TestClass
{
        public int ID { get; set; }
        public string text { get; set; }
}

我如何让STRING FOUR来到最后而不是第一,因为它不包含在lstCategories中?

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

int i = 0;
var orderStrings = lstTestClasses.OrderBy(x => 
                                 (i = lstCategories.IndexOf(x.text)) < 0 ? int.MaxValue : i)
                                 .ToList();

答案 1 :(得分:0)

由于未找到该值,IndexOf会返回-1,并将其一直放在集合的开头。

我建议检查IndexOf是否小于0,如果是,请将其设置为Int32.MaxValue,以便将其放在集合的末尾。

如:

TestClass test1 = new TestClass() { ID = 1, text = "STRING ONE" };
TestClass test2 = new TestClass() { ID = 2, text = "STRING TWO" };
TestClass test3 = new TestClass() { ID = 3, text = "STRING THREE" };
TestClass test4 = new TestClass() { ID = 4, text = "STRING FOUR" };

List<TestClass> lstTestClasses = new List<TestClass>();
lstTestClasses.Add(test1);
lstTestClasses.Add(test2);
lstTestClasses.Add(test3);
lstTestClasses.Add(test4);

List<string> lstCategories = new List<string>() { "STRING TWO", "STRING ONE", "STRING THREE" };

var orderStrings = lstTestClasses.OrderBy(x => {
    var index = lstCategories.IndexOf(x.text);
    return index < 0 ? Int32.MaxValue : index;
}).ToList();

foreach (var item in orderStrings)
{
    Console.WriteLine(item.text);
}