c# : how to read from specific index in List<person>

£可爱£侵袭症+ 提交于 2019-12-23 09:56:26

问题


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}

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:


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.

Docs are here; http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

Keep in mind you need to do bounds checking before access.




回答2:


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.

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

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.




回答3:


More information on your requirement / why you are accessing the list this way might help provide a better recommendation on approach but:

  1. If you want to use your list in this way frequently an Array or ArrayList may be a better option.
  2. 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)
  3. If you just know the index of the element, you can reference as both you and @evanmcdonnal describe.



回答4:


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";
    }
}



回答5:


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



回答6:


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

        }

    }
}


来源:https://stackoverflow.com/questions/18597619/c-sharp-how-to-read-from-specific-index-in-listperson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!