You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定国家数组顺序对Animal对象数组排序?

解决方案

场景1:仅保留指定国家的动物,按sortByCountries顺序排列

如果你只需要sortByCountries列表中出现的国家对应的动物,并且严格按照该列表的顺序输出,分组+顺序收集的方式效率最高:

// 先按Country分组,避免多次遍历allAnimals
var animalsGroupedByCountry = allAnimals
    .GroupBy(a => a.Country)
    .ToDictionary(g => g.Key, g => g.ToArray());

// 按sortByCountries的顺序提取对应分组的动物
var sortedAnimals = sortByCountries
    .SelectMany(country => 
        animalsGroupedByCountry.TryGetValue(country, out var group) ? group : Array.Empty<Animal>())
    .ToArray();

这种方法的优势:

  • 时间复杂度为O(n + m)(n是动物总数,m是指定国家数),大数据量下性能优于多次遍历查找
  • 逻辑清晰,直接匹配你要的顺序

场景2:保留所有动物,仅将指定国家的动物按顺序排到前面

如果需要保留所有动物,只是把sortByCountries里的国家对应的动物优先按顺序排列,其余动物排到最后,可以用自定义排序规则:

// 构建国家到排序索引的映射,快速查找
var countrySortIndex = sortByCountries
    .Select((country, idx) => new { country, idx })
    .ToDictionary(x => x.country, x => x.idx);

// 按索引排序,不在列表中的国家用最大int值排到最后
var sortedAnimals = allAnimals
    .OrderBy(a => countrySortIndex.TryGetValue(a.Country, out var idx) ? idx : int.MaxValue)
    .ToArray();

补充:修复Animal类的可访问性

你当前的Animal类字段是私有且无显式构造函数,实例化会报错,需要调整为:

class Animal
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public string Notes { get; set; }

    public Animal(int id, string name, string country, string notes)
    {
        Id = id;
        Name = name;
        Country = country;
        Notes = notes;
    }
}

关于你提到的遍历收集方法

你最初想到的遍历sortByCountries并逐个添加对应动物的方法是可行的,但用LINQ的SelectMany结合分组字典可以优化性能,避免重复遍历allAnimals。

内容的提问来源于stack exchange,提问作者scorpion35

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:11:29