基于类元素组织字典

本文关键字:字典 元素 于类 | 更新日期: 2023-09-27 18:11:27

我有一个将对象添加到字典中的程序。字典是用int和我的自定义Ship类设置的。问题是我需要通过类中的一个变量来组织船只。

船级为-

public class Ship
{
    public string Name { get; set; }
    public int Attack { get; set; }
    public int Engine { get; set; }
    public int Shield { get; set; }
    public string Team { get; set; }
    public string ShipClass { get; set; }
    public Ship(string name, int attack, int engine, int shield, string team, string shipClass)
    {
        Name = name;
        Attack = attack;
        Engine = engine;
        Shield = shield;
        Team = team;
        ShipClass = shipClass;
    }
}

我需要组织

Dictionary<int,Ship> ShipList = new Dictionary<int,Ship>();

由ShipList[我]。每艘船都有引擎。

基于类元素组织字典

A Dictionary是无序的,因此尝试对字典进行排序并将其保存在字典中是没有意义的。这将为您提供键/值(int/Ship)对的List,按Engine排序:

var orderedPairs = ShipList.OrderBy(x => x.Value.Engine).ToList();

这将为您提供一个有序的集合。注意,如果您不需要对所有船只进行排序,您可能应该使用where子句来限制这一点,以减少对所有船只进行排序的开销。

ShipList.Values.OrderBy(s => s.Attack);

如果你想确保实际的字典是有序的,你需要使用SortedDictionary类来代替,并提供你自己的IComparer。标准字典不支持按键排序

看一下OrderedDictionary或类似的泛型