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

您需要使用 aDictionary<string,int>而不是 a 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对于您的AA, BB,CC值,int对于20,30等。示例;

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