Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values of items in IList?

Tags:

c#

Is there any way to get the values of items in the IList? It goes like this:

Assume we have an IList list and a method private IList getValues(int ID)

then we initialize IList list like:

IList list = getValues(SelectedID)

After the processing, IList list now contains 2 elements, each with it's own collection:

[0]
 {
   GroupName = "test01"
   GroupID = 1
 }

[1]
 {
   GroupName = "test02"
   GroupID = 2
 }

How will I get the GroupName of the first element? I can't just call it like list[0].GroupName, can I?

like image 958
Don Avatar asked Apr 21 '14 09:04

Don


2 Answers

If you know the type of the object, you can use this to get what you want.

list.Cast<Group>().ElementAt(0).GroupName

Group as in your object name.

like image 146
Mohamed Avatar answered Sep 20 '22 03:09

Mohamed


Try the following, you need to create a list with your custom object. I created a dummy class here named CustomClass, and creating a list with the known type.

public class CustomClass
    {
        public string GroupName { get; set; }
        public int GroupID { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        List<CustomClass> list = new List<CustomClass>();
        foreach (var x in list) {
            Console.WriteLine(x.GroupName);
        }

    }
like image 25
Mez Avatar answered Sep 20 '22 03:09

Mez