如何通过另一个列表对对象列表进行排序

时间:2019-09-17 13:31:20

标签: c# linq

我有两节课:

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"
            },
        };

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

xxx
Foo
Bar
yyy

我尝试了以下代码:

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

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

2 个答案:

答案 0 :(得分:0)

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);
    }
}

答案 1 :(得分:0)

做到这一点:

  locations= locations.OrderBy(x => x.Address).ToList();
  var orderedPeopleList=new List<Person>();
  for (var i = 0; i < locations.Count(); i++)
  {
        peopelOrderedList.Add(people.FirstOrDefault(x => x.Address == locations[i].Address && peopelOrderedList.All(c => c.Name != x.Name)));
  }

  peopelOrderedList.RemoveAll(x => x == null);