c#:如何从 List<person> 中的特定索引读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18597619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# : how to read from specific index in List<person>
提问by user2740970
I have a class of persons and list collection as list contains all the values of person class such as :
我有一类人员和列表集合,因为列表包含人员类的所有值,例如:
List ilist has 2 values [0]={firstname,lastname} . [1]={firstname2,lastname2}
列表 ilist 有 2 个值 [0]={firstname,lastname} 。[1]={firstname2,lastname2}
now when i am iterating into the list i am able to print the list but i want to change the value of some parts of my list e.g in index 1 if i want to change the value of firstname2 to firstname3 i am not able to do it . Can anyone tell me how to print the list and then on that index changing any value of the index , i.e. firstname and secondname variable in the person class so that i can update my values Thanks
现在,当我迭代到列表时,我可以打印列表,但我想更改列表某些部分的值,例如在索引 1 中,如果我想将 firstname2 的值更改为 firstname3 我无法做到. 谁能告诉我如何打印列表,然后在该索引上更改索引的任何值,即 person 类中的 firstname 和 secondname 变量,以便我可以更新我的值谢谢
回答by evanmcdonnal
According to the docs on msdn you can use the familiar index operator (like on what you use on arrays). So myList[1].lastname = "new last name";
should do it for you.
根据 msdn 上的文档,您可以使用熟悉的索引运算符(就像您在数组上使用的那样)。所以myList[1].lastname = "new last name";
应该为你做。
Docs are here; http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
文档在这里;http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
Keep in mind you need to do bounds checking before access.
请记住,您需要在访问前进行边界检查。
回答by Matthew
More information on your requirement / why you are accessing the list this way might help provide a better recommendation on approach but:
有关您的要求/为什么以这种方式访问列表的更多信息可能有助于提供更好的方法建议,但是:
- If you want to use your list in this way frequently an Array or ArrayList may be a better option.
- That said, if your specific issue is determining the current element you want to change's ID you can use
IndexOf()
. (note this will loop the array to find the object's position) - If you just know the index of the element, you can reference as both you and @evanmcdonnal describe.
- 如果您想经常以这种方式使用您的列表,则 Array 或 ArrayList 可能是更好的选择。
- 也就是说,如果您的具体问题是确定要更改 ID 的当前元素,则可以使用
IndexOf()
. (注意这将循环数组以找到对象的位置) - 如果您只知道元素的索引,则可以参考您和@evanmcdonnal 的描述。
回答by Dustin Kingen
Lists can be modified directly using their indexer.
可以使用索引器直接修改列表。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
var list = new List<Person>
{
new Person
{
FirstName = "Bob",
LastName = "Carlson"
},
new Person
{
FirstName = "Elizabeth",
LastName = "Carlson"
},
};
// Directly
list[1].FirstName = "Liz";
// In a loop
foreach(var person in list)
{
if(person.FirstName == "Liz")
{
person.FirstName = "Lizzy";
}
}
回答by parfilko
I do not see where you can meet the problem:
我不知道您在哪里可以解决问题:
public class Persons
{
public Persons(string first, string last)
{
this.firstName = first;
this.lastName = last;
}
public string firstName { set; get; }
public string lastName { set; get; }
}
...
...
List<Persons> lst = new List<Persons>();
lst.Add(new Persons("firstname", "lastname"));
lst.Add(new Persons("firstname2", "lastname2"));
for (int i = 0; i < lst.Count; i++)
{
Console.Write("{0}: {2}, {1}", i, lst[i].firstName, lst[i].lastName);
if (i == 1)
{
lst[i].firstName = "firstname3";
lst[i].lastName = "lastname3";
Console.Write(" --> {1}, {0}", lst[i].firstName, lst[i].lastName);
}
Console.WriteLine();
}
}
Output:
输出:
0: lastname, firstname
1: lastname2, firstname2 --> lastname3, firstname3
回答by TheDanMan
I came here whilst searching for access specific index in object array values C#on Google but instead came to this very confusing question. Now, for those that are looking for a similar solution (get a particular field of an object IList that contains arrays within it as well). Pretty much similar to what the OP explained in his question, you have IList person and person contains firstname, lastname, cell etc and you want to get the firstname of person 1. Here is how you can do it.
我来到这里时在 Google 上搜索对象数组值 C# 中的访问特定索引,但却遇到了这个非常令人困惑的问题。现在,对于那些正在寻找类似解决方案的人(获取包含数组的对象 IList 的特定字段)。与 OP 在他的问题中解释的内容非常相似,您有 IList person 和 person 包含名字、姓氏、单元格等,并且您想获取人 1 的名字。这是您的方法。
Assume we have
假设我们有
IList<object> myMainList = new List<object>();
myMainList.Add(new object[] { 1, "Person 1", "Last Name 1" });
myMainList.Add(new object[] { 2, "Person 2", "Last Name 2" });
At first, I though this would do the trick:
起初,我认为这可以解决问题:
foreach (object person in myMainList)
{
string firstname = person[1].ToString() //trying to access index 1 - looks right at first doesn't it??
}
But surprise surprise, C# compiler complains about it
但出人意料的是,C# 编译器抱怨它
Cannot apply indexing with [] to an expression of type 'object'
无法将 [] 索引应用于“对象”类型的表达式
Rookie mistake, but I was banging my head against the wall for a bit. Here is the proper code
菜鸟的错误,但我的头撞在墙上了一会儿。这是正确的代码
foreach (object[] person in myMainList) //cast object[] NOT object
{
string firstname = person[1].ToString() //voila!! we have lift off :)
}
This is for any newbie like me that gets stuck using the same mistake. It happens to the best of us.
这适用于像我这样因同样错误而陷入困境的新手。它发生在我们中最好的人身上。
回答by CoderBaba
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
List<Person> list = new List<Person>();
Person oPerson = new Person();
oPerson.Name = "Anshu";
oPerson.Age = 23;
oPerson.Address = " ballia";
list.Add(oPerson);
oPerson = new Person();
oPerson.Name = "Juhi";
oPerson.Age = 23;
oPerson.Address = "Delhi";
list.Add(oPerson);
oPerson = new Person();
oPerson.Name = "Sandeep";
oPerson.Age = 24;
oPerson.Address = " Delhi";
list.Add(oPerson);
int index = 1; // use for getting index basis value
for (int i=0; i<list.Count;i++)
{
Person values = list[i];
if (index == i)
{
Console.WriteLine(values.Name);
Console.WriteLine(values.Age);
Console.WriteLine(values.Address);
break;
}
}
Console.ReadKey();
}
}
class Person
{
string _name;
int _age;
string _address;
public String Name
{
get
{
return _name;
}
set
{
this._name = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
this._age = value;
}
}
public String Address
{
get
{
return _address;
}
set
{
this._address = value;
}
}
}
}