自定义OrderBy列表列表

时间:2012-11-27 12:44:57

标签: c# linq

我想在列表上订购:

public List<Person> personList { get; set; };    

class Person
{
    public string Name{ get; set; };
    public List<Car> carList{ get; set; };
}

class Car
{
    public string Name { get; set; };
    public int PriceInMillions { get; set; };
}

我想对每个CarList的{​​{1}}进行排序,以便PersonList在列表顶部有CarList

输入:

BMW object(can be one or more)

必需输出:

Person: Name: 'ABC'
List<Car>:{{"x",25},{"y",25},{"BMW",26},{"x",25},{"BMW",25}}

Person: Name: 'DEF'
List<Car>:{{"BMW",21},{"y",25},{"BMW",26},{"x",25},{"BMW",20}}

我试图找到“宝马”的索引并将其与第一个索引交换,但它无效。

3 个答案:

答案 0 :(得分:1)

List<Car> orderedCarList = person.carList.OrderBy(s => (s.Name == "BMW") ? 0 : 1).ToList();
person.carList = orderedCarList;

答案 1 :(得分:0)

如果您想在原地排序,而不为每个人创建新列表或汽车,您可以

foreach(Person p in personList)
{
    p.carList.Sort((car1, car2) =>
        -(car1.Name == "BMW").CompareTo(car2.name == "BMW"));
}

答案 2 :(得分:0)

这是工作解决方案:

public List<Person> GetSortedList(List<Person> personList)
{
   foreach (var person in personList)
   {
       person.CarList=person.CarList.OrderByDescending(x => x.Name== "BMW").ToList();
   }
 return personList;
}