I have a function that takes Card objects and needs to sort them by their string value in a custom order. Each card can be any number from 2 to 10, or J, Q, K, or A. I want my function to sort the cards in this order: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A.
However, if I try to sort them with OrderBy(x => x.Value) , it will sort them by string. I have the function GetRankDictionary because I thought it would be helpful but I don't see If there is a way I could use it in a lambda expression for OrderBy's arguements.
class Program
{
public class Card
{
public string Value;
public string Suit;
public Card(string value, string suit)
{
Value = value;
}
}
static void Main(string[] args)
{
var cards = new List<Card>() { new Card("J", "Hearts"), new Card("8", "Hearts"), new Card("3", "Hearts"),
new Card("6", "Hearts"), new Card("9", "Hearts"), new Card("7", "Hearts"),
new Card("K", "Hearts"), new Card("A", "Hearts"), new Card("2", "Hearts")};
cards = SortCards(cards);
}
public static List<Card> SortCards(List<Card> cards)
{
var RankDictionary = GetCardRankDictionary();
// How to custom sort the cards in LINQ indicated by RankDictionary?
cards = cards.OrderBy(x => x.Value).ToList();
foreach (Card c in cards)
Console.WriteLine(c.Value);
return cards;
}
public static Dictionary<string, int> GetCardRankDictionary()
{
var dict = new Dictionary<string, int>();
var values = new string[] {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
var index = 2;
foreach (string s in values)
dict.Add(s, index++);
return dict;
}
}