Ant*_*ero 1 c# linq arrays sorting
示例我有一个数据
Person = [
{
Name: "AE1",
Country: "PH"
},
{
Name: "AE2",
Country: "LD"
},
{
Name: "AE3",
Country: "TW"
},
]
Run Code Online (Sandbox Code Playgroud)
我想按国家/地区排序,假设我放置了一个常量数组["TW", "PH", "LD"]。
结果将是 AE3、AE1、AE2。
您可以使用Array.IndexOf作为排序标准:
string[] countryOrders = {"GB", "TW", "SE"};
var personsByCountry = persons.OrderBy(p => Array.IndexOf(countryOrders, p.Country));
Run Code Online (Sandbox Code Playgroud)
如果一个国家不存在,它将排在第一位,因为返回 -1。如果你不想这样:
var personsByCountry = persons
.Select(p => (Person: p, Order: Array.IndexOf(countryOrders, p.Country)))
.OrderBy(x => x.Order == -1 ? 1 : 0)
.ThenBy(x => x.Order)
.Select(x => x.Person);
Run Code Online (Sandbox Code Playgroud)