c# - 如何按另一个列表对对象列表进行排序
问题描述
我有两节课:
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 进行此排序的最佳方法是什么?
解决方案
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);
}
}
推荐阅读
- php - 可以在我的数据库上一一提交请求吗?或按数组提交整体
- reactjs - redux redux-persist typescript 不能命名错误
- php - Pug 没有在模板端输出我的变量
- node.js - 如何在 Mongoose 中用他的索引号更新数组
- python - 如何在 Pandas,Pysimplegui 中找到最高和最低值并聚合成一个字符串
- bash - 使用 /dev/tcp/ 进行端口扫描时如何消除错误?
- php - 在 WooCommerce 中销售数量为 0 的商品
- c# - 我有旋转问题;旋转到目标;
- python - 在 Python 中使用低于 ASCII 127 的字符加密字符串
- git - 更改分支删除文件