首页 > 解决方案 > 如何按另一个列表对对象列表进行排序

问题描述

我有两节课:

class Location
{
    public string Address { get; set; }
}

class Person
{
    public string Address { get; set; }
    public string Name { get; set; }
}

然后我创建两个对象列表:

        var locations = new List<Location>()
        {
            new Location()
            {
                Address = "AA"
            },
            new Location()
            {
                Address = "BB"
            },
            new Location()
            {
                Address = "CC"
            },
            new Location()
            {
                Address = "BB"
            }
        };

        var people = new List<Person>()
        {
            new Person()
            {
                Address = "BB",
                Name = "Foo"
            },
            new Person()
            {
                Address = "CC",
                Name = "Bar"
            },
            new Person()
            {
                Address = "AA",
                Name = "xxx"
            },
            new Person()
            {
                Address = "BB",
                Name = "yyy"
            },
        };

我想要的是通过匹配位置列表中的地址属性来对人员列表进行排序。这是我想要的结果:

xxx
Foo
Bar
yyy

我试过这段代码:

var orderedPeopleList = people.OrderBy(p => locations.FindIndex(l => l.Address.Equals(p.Address)));

但它不能正常工作,最后两行的顺序错误。使用 linq 进行此排序的最佳方法是什么?

标签: c#linq

解决方案


var orderedPeopleList = new List<Person>();

foreach (var location in locations)
{
    var foundPeople = people.Where(p => p.Address == location.Address).FirstOrDefault();
    if (foundPeople != null)
    {
        orderedPeopleList.Add(foundPeople);
        people.Remove(foundPeople);
    }
}

推荐阅读