【问题标题】:How to sort items by rank using a dictionary如何使用字典按排名对项目进行排序
【发布时间】:2020-12-15 08:35:17
【问题描述】:

我有一个函数,它接受 Card 对象,需要按自定义顺序按它们的字符串值对它们进行排序。每张卡片可以是从 2 到 10 的任意数字,或者 J、Q、K 或 A。我希望我的函数按以下顺序对卡片进行排序:2、3、4、5、6、7、8、9、10 , J, Q, K, A.

但是,如果我尝试使用 OrderBy(x => x.Value) 对它们进行排序,它将按字符串对它们进行排序。我有 GetRankDictionary 函数,因为我认为它会有所帮助,但我不知道是否有办法在 OrderBy 争论的 lambda 表达式中使用它。

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;

    }

}

【问题讨论】:

  • 您可以将属性public int NumValue 添加到表示具有int 的卡的值的类Cards 中。数字“2”到“9”将是它们对应的 int 值,“J”== 11、“Q”== 12 等,在构造函数中使用开关设置。顺便说一句,您是否故意遗漏了“10”?另一种解决方案是比较器:docs.microsoft.com/en-us/dotnet/api/…
  • 只需给您的Card 一个额外的Rank 属性,然后对其进行排序
  • @JohanP 的建议很简单,您将需要该属性或其他排名列表。有些人喜欢使用IComparer&lt;T&gt;IComparable&lt;T&gt; 接口来执行此操作,stackoverflow.com/a/26868916/495455 - 然后您可以使用内置的排序功能。
  • @cad 我不小心漏掉了 10 个。感谢您的关注。

标签: c# list sorting dictionary


【解决方案1】:

这真的很简单。你的代码就差不多了。

试试这个:

public static List<Card> SortCards(List<Card> cards)
{
    var RankDictionary = GetCardRankDictionary();

    cards = cards.OrderBy(x => RankDictionary[x.Value]).ToList();

    foreach (Card c in cards)
        Console.WriteLine(c.Value);

    return cards;
}

public static Dictionary<string, int> GetCardRankDictionary() =>
    new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" }
        .Select((x, n) => (x, n))
        .ToDictionary(z => z.x, z => z.n);

在您的示例数据上运行它会给我:

2
3
6
7
8
9
J
K
A

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2012-02-18
    相关资源
    最近更新 更多