我有一个国家清单.我想按字母顺序排序,除了我想放在第一个的两个国家/地区[英] I have a list of countries. I'd like to sort it alphabetically, except for two countries which I'd like to put first

本文是小编为大家收集整理的关于我有一个国家清单.我想按字母顺序排序,除了我想放在第一个的两个国家/地区的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个国家清单.我想按字母顺序排序,除了我想放在第一位的两个国家.有没有简单的方法来修改

from country in Countries
orderby country.Name
select country

实现这一目标?

推荐答案

尝试以下方法:

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

其他推荐答案

您可以使用此技巧:

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

其他推荐答案

您的原始列表,其中包含每个国家.

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

本文地址:https://www.itbaoku.cn/post/1557178.html

问题描述

I have a list of countries. I'd like to sort it alphabetically, except for two countries which I'd like to put first. Is there a simple way to modify

from country in Countries
orderby country.Name
select country

to accomplish this?

推荐答案

Try this:

var specialCountries = new[] { "America", "England" };

from country in Countries
orderby specialCountries.Contains(country.Name) descending, country.Name
select country

If this isn't LINQ-to-Objects, you might need to write it slightly differently for it to work, e.g. this might work

from country in Countries
orderby (country.Name == "America" || country.Name == "England") descending, country.Name
select country

其他推荐答案

You can use this trick:

var ordered = Countries.OrderByDescending(c => ConditionHere)
                       .ThenBy(c => c.Name);

for example:

var priorCountries = new[]{ "Italy", "France" };
var ordered = Countries.OrderByDescending(c => priorCountries.Contains(c.Name))
                       .ThenBy(c => c.Name);

其他推荐答案

Your original list, which contains every country.

var originalList = new List<string> { "B", "A", "E", "D", "C", "F" };

An exclusionary list, where you provide the order of items you'd like at the front.

var items = new List<string> { "E", "F" };

Your results.

items.AddRange(originalList.Except(items)
                           .OrderBy(q => q));