7

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

user2740970
  • 137
  • 3
  • 4
  • 6
  • Hey can you post your code? Loop? – Deepak Ingole Sep 03 '13 at 16:58
  • 1
    It's quite hard to follow your pseudo-code/description. `List` provides an indexer, so you can access it just like an array. If you've tried that and had a problem, it would really help if you'd show a short but complete program demonstrating what you tried and what went wrong. – Jon Skeet Sep 03 '13 at 16:59
  • If you find it you can update it.. this is how you find it.. http://stackoverflow.com/questions/9854917/how-can-i-find-a-specific-element-in-a-c-sharp-list – Yosi Dahari Sep 03 '13 at 17:00
  • post the code as @captain said – SamuraiJack Sep 03 '13 at 17:04
  • What does "i am not able to do it" mean? Does the code not compile? Do you get a runtime error? Does it seem to work, but you don't see the change? Show us the definition of your `Person`, and also show us the code that fails ... and tell us what kind of failure you're getting. – Jim Mischel Sep 03 '13 at 17:04
  • IList listA= new ArrayList(); for (int i = 0; i < listA.Count; i++) { Console.WriteLine(listA[i].ToString()); } – user2740970 Sep 03 '13 at 17:09
  • so my listA contains two values from Person class , when i see the values of listA indexes it is like [0]= {"firstname","lastname"} where in index 0 FirstName="firstname" and secondname="secondname" and same value for index 1 but now i want to change the value of lastname in index 1 . I am able to get the index 1 values but each value is linked to the Person class where values are coming from and setting if changes and this part of the code is required . Suppose i get the index 1 value ,i.e "FirstName" ,"secondname" but how to access the variables of the person which is linked in each index – user2740970 Sep 03 '13 at 17:10
  • So you have a `List`. Is the type `Person` really a class, and not a struct? Because then you might just use `listA[0].FirstName = "firstname3";`. The indexer `[0]` returns a new reference to the same object instance in this case (reference type), so you should be OK with that. – Jeppe Stig Nielsen Sep 03 '13 at 17:24
  • OK, I understand you have an `ArrayList`. That makes things much more messy. Something like `((Person)listA[0]).FirstName = "firstname3";`. You should really change to the generic `List<>` class and never use `ArrayList`. – Jeppe Stig Nielsen Sep 03 '13 at 17:29
  • thanks mate i have found the solution thanks again – user2740970 Sep 03 '13 at 17:37

6 Answers6

2

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 1
    my code is IList _ilist= new ArrayList(); FileReader(fileB, ref _ilist); and i am reading data from the file and adding into the list – user2740970 Sep 03 '13 at 17:18
  • @user2740970 Try to use generic `List` instead of `ArrayList` class. It will make life easier for you. – Jeppe Stig Nielsen Sep 03 '13 at 17:26
  • @user2740970 your question is unclear then. In the title you say you're using `List` which means you're using the generic list ( `List` ) with the type argument as Person. `ArrayList` is a different class entirely and in general is not used in new code. – evanmcdonnal Sep 03 '13 at 17:42
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.

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.

TheDanMan
  • 1,746
  • 1
  • 17
  • 22
  • `foreach (object[] person in myMainList)` this gives me `Cannot convert type 'ConsoleApplication1.Readings' to 'object[]'` error – Moeez Apr 18 '19 at 09:59
  • @Faisal, looks like you are using a concrete type and not object[]. Rather use "foreach (var person in myMainList)" if using the new c# – TheDanMan Apr 26 '19 at 14:04
1
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;
            }

        }

    }
}
CoderBaba
  • 11
  • 2
  • Consider expanding your answer to explain to the asker why this achieves the desired result, possibly linking to documentation. As is, this is only marginally useful. – Joshua Dwire Sep 01 '15 at 21:03
0

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.
Matthew
  • 9,851
  • 4
  • 46
  • 77
0

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";
    }
}
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • i have posted a new question here because i am not able to answer my question http://stackoverflow.com/questions/18598129/c-sharp-how-to-read-index-variables-linked-to-the-class-in-a-list – user2740970 Sep 03 '13 at 17:27
0

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
parfilko
  • 1,308
  • 11
  • 12