2

リストを作成していて、リストに追加されたアイテムの値を設定してから、その値を取得して表示したいと思います。

// Create a list of strings

List<string> AuthorList = new List<string>();

AuthorList.Add("AA");

AuthorList.Add("BB");

AuthorList.Add("CC");

AuthorList.Add("DD");

AuthorList.Add("EE");

// Set Item value

AuthorList["AA"] = 20;

// Get Item value

Int16 age = Convert.ToInt16(AuthorList["AA"]);

// Get first item of a List

string auth = AuthorList[0];

Console.WriteLine(auth);

// Set first item of a List

AuthorList[0] = "New Author";

しかし、エラーが発生しました

「「System.Collections.Generic.List.this[int]」に最適なオーバーロードされたメソッドの一致には、いくつかの無効な引数があります」

このコードを修正するのを手伝ってください。

4

3 に答える 3

1

キーペアを保存する場合の単一値のリストは、Dictionaryを使用します。

Dictionary<string,int> AuthorList  = new Dictionary<string,int>();
AuthorList.Add("AA", 20);
AuthorList.Add("BB", 30);
于 2013-01-18T09:09:43.463 に答える
1

Dictionary<string,int>の代わりにを使用する必要がありますList<string>

var authorAges = new Dictionary<string,int>();

authorAges.Add("AA",60);
authorAges.Add("BB",61);
authorAges["CC"] = 63; //add or update

// Set Item value
authorAges["AA"] = 20;

// Get Item value
int age = authorAges["AA"];

// Get first item of a List
string auth = authorAges.Keys.First();
Console.WriteLine(auth);

// Set first item of a List 
// (You can't change the key of an existing item, 
//  but you can remove it and add a new item)
var firstKey = authorAges.Keys.First();
authorAges.Remove(firstKey);
authorAges["New author"] = 32;

辞書に「最初」がないということは、何の価値もありません。クラスを作成し、Authorそれらのリストを用意する必要があるかもしれません:

class Author 
{ 
   public string Name {get; set;}
   public int Age {get; set;}
}

それで

var authors = new List<Author>();

authors.Add(new Author { Name = "AA" };
authors.Add(new Author { Name = "BB"};

// Get first item of a List
Author firstAuthor = authors[0];
Console.WriteLine(
    "First author -- Name:{0} Age:{1}",firstAuthor.Name, firstAuthor.Age);

// Get Item value
int age = authors[1].Age

// Set first item of a List 
authors[0] = new Author { Name = "New Author"};
于 2013-01-18T09:10:33.447 に答える
1

ではキーペアを使用できませんList。使ってみてくださいDictionary<TKey, TValue>

キーと値のコレクションを表します。

試してみてください;

Dictionary<string,int> YourAuthorList  = new Dictionary<string,int>();

stringあなたのAABBCC値、、intなど。2030

YourAuthorList.Add("AA", 20);
于 2013-01-18T09:11:06.890 に答える