'After calling .OrderBy the resulting List is not Sorted
I have a class called ShipPosition that looks like this:
public int nodesHit = 0;
PositionNode currentNode;
I want to have a list of ships called shipPositionsin the order of most nodes hit to least. I already have a list of all the ships I want to order in a variable called allShips and so, to do this I used .OrderBy() in this line of code:
List<ShipPosition> shipPositions = allShips.OrderByDescending(ship => ship.nodesHit).ToList();
Yet shipPositions stay identical to allShips.
Can you please tell me what I am missing?
Solution 1:[1]
seemed to work ok for me here is the fiddle https://dotnetfiddle.net/5oQO3B
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Ship> ships= new List<Ship>();
ships.Add(new Ship{NodesHit = 5});
ships.Add(new Ship{NodesHit = 10});
ships.Add(new Ship{NodesHit = 3});
ships.Add(new Ship{NodesHit = 9});
ships.Add(new Ship{NodesHit = 1});
foreach (Ship ship in ships.OrderByDescending(ship => ship.NodesHit))
{
Console.WriteLine(ship.NodesHit.ToString());
}
}
}
public class Ship{
public int NodesHit {get; set;}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bryan Dellinger |
