C# Sorting list by another list

前端 未结 4 1118
情书的邮戳
情书的邮戳 2020-12-21 23:33

I have now 2 lists:

list names;
list numbers;

and I need to sort my names based on the values in numbers. I\'ve be

4条回答
  •  天涯浪人
    2020-12-21 23:48

    To complement Tims answer, you can also use a custom data structure to associate one name with a number.

    public class Person
    {
        public int Number { get; set; }   // in this case you could also name it ID
        public string Name { get; set; }
    }
    

    Then you would have a List persons; and you can sort this List by whatever Attribute you like:

    List persons = new List();
    persons.Add(new Person(){Number = 10, Name = "John Doe"});
    persons.Add(new Person(){Number = 3, Name = "Max Muster"});
    
    // sort by number
    persons = persons.OrderBy(p=>p.Number).ToList();
    
    // alternative sorting method
    persons.Sort((a,b) => a.Number-b.Number);
    

提交回复
热议问题