我有一份国家/地区列表。我想按字母顺序排序,除了我想先放的两个国家。有没有一种简单的方法来修改
from country in Countries
orderby country.Name
select country
要做到这一点吗?
答案 0 :(得分:10)
你可以使用这个技巧:
var ordered = Countries.OrderByDescending(c => ConditionHere)
.ThenBy(c => c.Name);
例如:
var priorCountries = new[]{ "Italy", "France" };
var ordered = Countries.OrderByDescending(c => priorCountries.Contains(c.Name))
.ThenBy(c => c.Name);
答案 1 :(得分:5)
试试这个:
var specialCountries = new[] { "America", "England" };
from country in Countries
orderby specialCountries.Contains(country.Name) descending, country.Name
select country
如果这不是LINQ-to-Objects,您可能需要稍微改写它才能使其工作,例如:这可能有用
from country in Countries
orderby (country.Name == "America" || country.Name == "England") descending, country.Name
select country
答案 2 :(得分:1)
原始列表,其中包含每个国家/地区。
var originalList = new List<string> { "B", "A", "E", "D", "C", "F" };
排他性列表,您可以在其中提供您在前面所需的项目顺序。
var items = new List<string> { "E", "F" };
您的结果。
items.AddRange(originalList.Except(items)
.OrderBy(q => q));
答案 3 :(得分:0)
试试这个:
from country in countries
orderby (country.Name = "USA" ? 0 : 1), country.Name
select country
当然,您需要更改条件,但重点是您可以在orderby子句中执行一些评估。