2017-09-10 1 views
1

여기 학생.목록 < > 사전 < K,List< > 내부> (C#)

현재 C# 프로젝트 작업. 나는 카드 < 카드>를 만들고, < 사전 문자열, 목록 < 카드>를 생성해야합니다.

목록은 독립적으로 생성되고 사전은 카드 모음을 보유합니다. 컬렉션에서 카드를 추가하거나 제거 할 수 있습니다.

컬렉션에 카드를 추가하는 데 문제가 있습니다. 사용자 입력에서 목록의 색인 번호를 얻었으므로 색인에 따라 사전의 값을 간단히 업데이트하려고합니다.

오류를 발생시키는 행이 여기에 있습니다. 이 오류는 System.Collections.Generic.List < filename.CardClass> '

나는 내 인생에 대한

알아낼 수없는 것을 그 수단과 방법을 암시 적 유형'< filename.CardClass> ' 로 변환 할 수 없습니다 입니다 내가 Dictionary<string, List<Card>> 및을 입력한다 _collections 가정

public void AddToCollection() 
    { 
     PrintValuesCollections<string, List<Card>>(_collections); 
     Console.WriteLine("Type in the name of the collection to add a card to:"); 
     string input = Console.ReadLine(); 

     bool found = _collections.ContainsKey(input); 
     if (found) 
     { 
      Console.WriteLine("List of current cards to choose from:"); 

      for (int i = 0; i < _cards.Count; i++) 
      { 
        Console.WriteLine("Index number:\r\n"+i+"Card Info:\r\n"+_cards[i]+"\n"); 
      } 

      Console.WriteLine("Type in the index of the card from the list to add to the collection:"); 
      string cardSelection = Console.ReadLine(); 
      int cardSelectionIndex = 0; 
      while (!int.TryParse(cardSelection, out cardSelectionIndex)) 
      { 
       Console.Write("Please enter a number from the list above: "); 
       input = Console.ReadLine(); 
      } 

      _collections[input] = _cards[cardSelectionIndex]; 
      _cards.RemoveAt(cardSelectionIndex); 
     } 
     else 
      Console.WriteLine("Collection name not found."); 
    } 
+0

'_collections [입력] .Add (_cards [cardSelectionIndex]);'? – flakes

+0

확실치 않지만 새로운 고유 키를 추가하지 않습니까? 전에 언급 했어야 할 것은 이미 생성 된 키를 가지고 있으며 단순히 사용자의 키 입력을 기반으로 값을 업데이트하려고합니다. –

답변

3

: 그것을 해결하기 위해 ..

_collections[input] = _cards[cardSelectionIndex]; 

여기에 내 현재 코드 블록이다 (210)는 그래서 당신이 뭘 하려는지입니다 List<Card>

입니다 :

//_collections[input] = _cards[cardSelectionIndex]; 
List<Card> a = _collections[input]; 
Card b = _cards[cardSelectionIndex]; 
a = b; 

공지 사항이 ab의 종류. 이 올바르게 오류가 있습니다 : "Cannot implicitly convert type '<filename.CardClass>' to System.Collections.Generic.List<filename.CardClass>'는"

는 당신이 아마하고 싶은 것은 그 목록에 카드를 추가입니다

List<Card> a = _collections[input]; 
Card b = _cards[cardSelectionIndex]; 
a.Add(b); 

아니면 제가 예외 조금 설명하려고 단순히

_collections[input].Add(_cards[cardSelectionIndex]); 
+0

그건 의미가 있습니다. 설명 부스러기 주셔서 감사합니다! 다른 스레드를 열 필요가 없습니다. 사용자 입력 키를 기반으로 목록을 인쇄해야합니다. 현재 사용중입니다. (int i = 0; i <_collections.Keys (input) .Count; i ++) { Console.WriteLine ("인덱스 번호 : \ r \ n"+ i + "카드 정보 : \ r \ n "+ _cards [i] +"\ n "); } 하지만 비 호출 멤버를 제공합니다. Dictionary > .keys는 메서드처럼 사용할 수 없습니다. 아이디어가 있으십니까? –

+0

@DylanColeDuke 문제가 없습니다! 나머지 일요일을 만끽하십시오 : – flakes

+0

'_cards'리스트를 인쇄하려면'for' 루프에서 그리스트를 사용해야합니다. 'for (int i = 0; i <_cards.Count; i ++) ... ' – flakes

1

조금 더 그림.

그런 다음 다른 아무것 고유 키 액세스 KeyValuePair<string,List<Card>>의 목록입니다없는 Dictionary<string,List<Card>>을 만들 수 있습니다. 즉, 사전의 모든 항목은 string 유형의 키로 색인화 된 카드 목록입니다. 예를 들어

:

Key | Value 
"hearts" | List<Card> {1, 2, 7, 8, Queen} 
"spades" | List<Card> {King, Ace} 

는 예외는 단지 하나의 카드 한 벌의 카드를 대체하려고, 당신을 말하고 이제 어떻게.

당신이 할 것입니다 :

List<Card> spades = collection["spades"]; // King, Ace 
spades = new Card(Queen); // Your Exception 

그러나 이것은 당신이 할 수 있습니다 것입니다 :

Key | Value 
"hearts" | List<Card> {1, 2, 7, 8, Queen} 
"spades" | List<Card> {King, Ace, Queen} 

그리고 만약 :

List<Card> spades = collection["spades"]; // King, Ace 
spades.Add(Card(Queen)); // Add an element to the List 

이제 사전은 다음과 같습니다 콜렉션에 "클럽"데크를 추가하려면 다음 번호로 전화하십시오.

,210
collection.Add("clubs", new List<Card> {1, 2, 3, Ace}); 

또는 짧은 :

collection["clubs"] = new List<Card> {1, 2, 3, Ace}; 

그러나 키가 사전에 이미와 그렇지 않은 경우 두 번째 그냥 새 항목을 만들 것입니다 경우, 첫 번째는 duplic 키 예외를 발생시킬 수 있습니다주의 하시고 기존의 것을 대체하거나 기존의 것을 오버라이드합니다.

+0

그레이트 포스트! ** 고유 키 **가 모두에게 명확하지 않은 경우 ... 모든 사전을 키 - 값 - 쌍 목록으로 나타낼 수 있지만 모든 키 - 값 쌍 목록이 사전이 될 수는 없다는 점에 유의해야합니다. 사전에는 도메인간에 고유하거나 0의 일치가 필요합니다. 'key-> value'. 일반적인 키 - 값 - 쌍 목록은 도메인 값당 여러 개의 대응을 가질 수 있습니다. 이 경우 키가 고유하지 않을 수도 있습니다. – flakes

+0

@flakes 당신은 절대적으로 옳습니다. 의견을 보내 주셔서 감사합니다. –

관련 문제