c#:如何从列表中的特定索引中读取< person> [英] c# : how to read from specific index in List<person>

查看:178
本文介绍了c#:如何从列表中的特定索引中读取< person>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类人和列表集合,因为列表包含人类
的所有值,例如:

I have a class of persons and list collection as list contains all the values of person class such as :

列表ilist有2个值[0 ] = {firstname,lastname}。 [1] = {firstname2,lastname2}

List ilist has 2 values [0]={firstname,lastname} . [1]={firstname2,lastname2}

现在当我迭代到列表中,我能够打印列表,但我想更改某些部分的值我的列表例如在索引1如果我想将firstname2的值更改为firstname3我不能这样做。任何人都可以告诉我如何打印列表,然后根据该索引更改索引的任何值,即person类中的firstname和secondname变量,以便我可以更新我的值
感谢

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

推荐答案

我在这里搜索在Google对象数组值C#中访问特定索引,而是引入了这个令人困惑的问题。现在,对于那些正在寻找一个类似的解决方案(获取一个对象IList的特定字段,其中包含数组)。与他在问题中解释的OP非常相似,你有IList的人和人包含姓,姓,单元格等,你想得到人1的名字。这是你可以做到的。

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.

假设我们有

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??
}

但令人惊讶的是,C#编译器抱怨它

But surprise surprise, C# compiler complains about it


无法使用[]将索引应用于类型为object的表达式

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.

这篇关于c#:如何从列表中的特定索引中读取&lt; person&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆