获取并设置与指定索引关联的值

时间:2013-01-18 09:08:34

标签: c# list

我正在创建一个列表,并希望设置列表中添加的项目的值,然后检索该值以显示。

// 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]'有一些无效   参数“

帮我修改此代码。

2 个答案:

答案 0 :(得分:1)

如果您想使用Dictionary存储密钥对,则单个值列表。

Dictionary<string,int> AuthorList  = new Dictionary<string,int>();
AuthorList.Add("AA", 20);
AuthorList.Add("BB", 30);

答案 1 :(得分: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"};