Search code examples
c#linqcollectionsienumerablekey-value

"Connot implicitily convert type 'System.Generic.Collection.IEnumerable<int> to <int>


I am building a program that will take two user-selected cards from a standard deck of cards. The deck is made of KeyValuePair<int, string>s where it is set out as number then suit. After the user selects two cards, I need the program to add the integer parts of the cards together. I do not know how to get the Key parts of a KeyValuePair.

I know my code below obviously won't work, but I've included the image to show what I'm trying to do. My program should take the key value from the KeyValuePairs at the 'chosen card index, instead, it provides the error in the title of this post.

Picture of my Current Code

I have tried to convert the whole of the line to a string using Convert.ToInt32, but it also does not work. I have looked everywhere for a precise answer to this problem but with no luck.

Here's all the rest of the relevant code:

    public static List<KeyValuePair<int, string>> Player1Hand = new 
    List<KeyValuePair<int, string>>(10); // creating the player's hand

    public static int chosencard;
    public static int player1total;
    public static string input;

    input = Console.ReadLine();
    chosencard2 = Int32.Parse(input);

    player1total = Hand.Player1Hand[chosencard];
    Console.WriteLine("Player 1's total is " + player1total);

Thanks, everyone for the help in advance.


Solution

  • Your Player1Hand is a List of KeyValue<int, string>. So what you are currently doing is accessing that pair, while you should access the key of that pair at the given index.

    I think, with the information you gave me, this should do the trick:

    player1Total += Hand.Player1Hand[chosencard].Key