0

I have a program where I'm adding objects to a dictionary. The dictionary is set up with an int and my custom 'Ship' class. The problem is I need to organize the ships by a variable in the class.

The ship class is -

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

And I need to organize

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

by ShipList[i].Engine where i goes down through each ship I have. Any help would be great.

4 Answers4

0

A Dictionary is unordered, so there's no sense in trying to sort the dictionary and keep it in a dictionary. This will give you a List of key/value (int/Ship) pairs, ordered by Engine:

var orderedPairs = ShipList.OrderBy(x => x.Value.Engine).ToList();
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

This will provide you with an ordered collection. Note if you don't need to sort all of the ships, you should probably limit this with a where clause to reduce the overhead of sorting all the ships.

ShipList.Values.OrderBy(s => s.Attack);
N-ate
  • 6,051
  • 2
  • 40
  • 48
0

If you want to make sure actual dictionary is ordered, you would need to use SortedDictionary class instead and supply your own IComparer. Standard Dictionary doesn't support sorting by key.

user3613916
  • 232
  • 1
  • 10
0

Take a look at an OrderedDictionary or a generic equivalent

Community
  • 1
  • 1
Carra
  • 17,808
  • 7
  • 62
  • 75