获取具有不同键的重复值的枚举变量的值

时间:2016-04-14 12:43:26

标签: c# enums

我有52张扑克牌的枚举,如下所述,

public enum Card
{
        AceClubs = 11,
        AceDiamonds = 11,
        AceHearts = 11,
        AceSpades = 11,
        DeuceClubs = 2,
        DeuceDiamonds = 2,
        DeuceHearts = 2,
        DeuceSpades = 2,
        EightClubs = 8,
        EightDiamonds = 8,
        EightHearts = 8,
        EightSpades = 8,
        FiveClubs = 5,
        FiveDiamonds = 5,
        FiveHearts = 5,
        FiveSpades = 5,
        FourClubs = 4,
        FourDiamonds = 4,
        FourHearts = 4,
        FourSpades = 4,
        JackClubs = 11,
        JackDiamonds = 11,
        JackHearts = 11,
        JackSpades = 11,
        KingClubs = 13,
        KingDiamonds = 13,
        KingHearts = 13,
        KingSpades = 13,
        NineClubs = 9,
        NineDiamonds = 9,
        NineHearts = 9,
        NineSpades = 9,
        QueenClubs = 12,
        QueenDiamonds = 12,
        QueenHearts = 12,
        QueenSpades = 12,
        SevenClubs = 7,
        SevenDiamonds = 7,
        SevenHearts = 7,
        SevenSpades = 7,
        SixClubs = 6,
        SixDiamonds = 6,
        SixHearts = 6,
        SixSpades = 6,
        TenClubs = 10,
        TenDiamonds = 10,
        TenHearts = 10,
        TenSpades = 10,
        ThreeClubs = 3,
        ThreeDiamonds = 3,
        ThreeHearts = 3,
        ThreeSpades = 3
  }

我想从枚举

创建一个列表
 var cards = Enum.GetValues(typeof(Card));

但它会在列表中返回重复的键。

enter image description here

4 个答案:

答案 0 :(得分:1)

使用Enum.GetNames代替Enum.GetValues

答案 1 :(得分:0)

你的错误是对不同的东西使用相同的值。枚举不具有重复值(除非它们的含义相同)。

当程序运行时,枚举将保持为整数 - 而不是名称。

然后调试器从程序(4)中获取一个整数,并将其显示为它可以找到的第一个枚举(FourClubs)。这只是为了方便调试 - 程序仍然使用整数(4)。

答案 2 :(得分:0)

我建议使用两个枚举 suit value

  public enum CardSuit {
    Clubs = 1,
    Diamonds = 2,
    Hearts = 3,
    Spades = 4,
  };

  public enum CardValue {
    Ace = 1,
    Deuce = 2, 
    ...
    King = 13,
  };

然后实施扩展方法以获取实际卡片值(因为JackAce都对应11):

  public static class ValueExtensions() {
    public static int ActualValue(this CardValue value) { 
      if (value == CardValue.Ace)
        return 11; // Ace is 11
      else
        return (int) value;
    } 
  }

最后

  public class Card {
    public Card (CardSuit suit, CardValue value) {
      Suit = suit;
      Value = value;  
    }

    public CardSuit Suit {get; private set;} 
    public CardValue Value {get; private set;} 
  }

  ...

  Card[] pack = Enum
    .GetValues(typeof(CardSuit))
    .OfType<CardSuit>()
    .SelectMany(suit => Enum
      .GetValues(typeof(CardValue))
      .OfType<CardValue>()
      .Select(value => new Card(suit, value)))
    .ToArray();

  //TODO: Shuffle the pack here
  Card[] hand = pack.Take(5).ToArray();

  int handValue = hand.Sum(card => card.Value.ActualValue()); 

答案 3 :(得分:-1)

您可以使用Linq:

从阵列中删除重复项
\