排序基于的另一个列表中的内容的列表内容、列表、列表中

2023-09-05 03:21:23 作者:忘初心i

我有一个包含整数列表和包含保存两个整数和字符串一类另一个列表的列表。

I have a list that contains a list of integers and another list that contains a class that holds both an integer and a string.

我试图做的是按字母顺序排序我的名单,把存在于第一个列表的第一项。这是我的code和预期的输出:

What I'm trying to do is sort my list alphabetically, putting the entries that exist in the first list first. Here is my code and expected output:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var myList = new List<int>();
        myList.Add(5);
        myList.Add(15);

        var myclasses = new List<MyClass>();
        myclasses.Add(new MyClass {MyId = 8, MyString = "Entry1"});
        myclasses.Add(new MyClass {MyId = 12, MyString = "Entry2"});
        myclasses.Add(new MyClass {MyId = 1, MyString = "Entry3"});
        myclasses.Add(new MyClass {MyId = 15, MyString = "Entry4"});
        myclasses.Add(new MyClass {MyId = 9, MyString = "Entry5"});
        myclasses.Add(new MyClass {MyId = 5, MyString = "Entry6"});

        foreach (MyClass c in myclasses.OrderBy(z => myList.Contains(z.MyId)).ThenBy(z => z.MyString )) {
            Console.WriteLine("{0} ==> {1}", c.MyId, c.MyString);
        }

        // I'm expecting this output:
        //
        // 15 ==> Entry4
        // 5 ==> Entry6
        // 8 ==> Entry1
        // 12 ==> Entry2
        // 1 ==> Entry3
        // 9 ==> Entry5
    }

    public class MyClass {
        public int MyId { get; set; }
        public string MyString { get; set; }
    }
}

正如你可以从我的期望的输出看,我想 Entry6 Entry4 最先出现,因为他们出现在第一个列表。然后,我只是想要一个字母列表。我想我的LINQ说法是正确的,但它不是给我正确的结果。任何帮助将是AP preciated。

As you can see from my expected output, I want Entry6 and Entry4 to appear first since they appear in the first list. Then I just want an alphabetical list. I thought my LINQ statement would be correct, but its not giving me the correct results. Any help would be appreciated.

推荐答案

简单地反转 myList.Contains 条件:

foreach (MyClass c in myclasses.OrderBy(z => !myList.Contains(z.MyId)).ThenBy(z => z.MyString )) {
       Console.WriteLine("{0} ==> {1}", c.MyId, c.MyString);
}

我相信这是因为被视为 1 ,而假是 0