C# 获取并设置与指定索引关联的值
我正在创建一个列表,希望设置添加到列表中的项目的值,然后检索该值以显示C# 获取并设置与指定索引关联的值,c#,list,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
// 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";
//创建字符串列表
List AuthorList=新列表();
作者列表。添加(“AA”);
作者列表。添加(“BB”);
AuthorList.Add(“CC”);
作者列表。添加(“DD”);
作者列表。添加(“EE”);
//设置项目值
作者列表[“AA”]=20;
//获取项目值
Int16 age=Convert.ToInt16(AuthorList[“AA”]);
//获取列表的第一项
字符串auth=AuthorList[0];
控制台写入线(auth);
//设置列表的第一项
AuthorList[0]=“新作者”;
但是发生了错误
“的最佳重载方法匹配”
“System.Collections.Generic.List.this[int]”具有一些无效属性
“论据”
请帮助我更正此代码。如果要存储密钥对,请列出单个值
Dictionary AuthorList=new Dictionary();
添加(“AA”,20);
添加(“BB”,30);
您需要使用列表,而不是列表
然后
var authors=newlist();
添加(新作者{Name=“AA”};
添加(新作者{Name=“BB”};
//获取列表的第一项
Author firstAuthor=作者[0];
控制台写入线(
“第一作者——姓名:{0}年龄:{1}”,firstAuthor.Name,firstAuthor.Age);
//获取项目值
int age=作者[1]。年龄
//设置列表的第一项
作者[0]=新作者{Name=“新作者”};
您不能与一起使用密钥对。请尝试使用
表示键和值的集合
尝试
Dictionary<string,int> YourAuthorList = new Dictionary<string,int>();
你所说的无效行到底是什么意思还不清楚。你到底想达到什么目的?给AuthorList[“AA”]分配一个20表示什么
?20从何而来?List类有三个属性–Capacity、Count和Item。Item属性用于获取和设置与指定索引关联的值。因此,我只想设置然后获取值。
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;
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"};
Dictionary<string,int> YourAuthorList = new Dictionary<string,int>();
YourAuthorList.Add("AA", 20);