DanCaparroz
DanCaparroz

Reputation: 820

Getting all elements from a list of objects

I got an object list with some attributes and after populating this list, I want to get all the elements from a specific variable of this object and put it inside a new INT list. I'll try to example:

public class Obj1 
{
   public int id {get; set; }
   public string name {get; set; }
   public int? age {get; set; }
}

public List<int> GetAgeList(List<Obj1> list)
{
  List<int> ageList = list.age;//The idea is add all ages into the list..
  return ageList;
}

Thanks!

Upvotes: 0

Views: 529

Answers (2)

Ima Geekah
Ima Geekah

Reputation: 13

public class Main
{
    //Create objects
    Obj1 someObj = new Obj1();
    Obj1 someObj2 = new Obj1();
    Obj1 someObj3 = new Obj1();

    //You should set some values

    //Make a list with them    
    List<Obj1> listSomeObj = new List<Obj1>();

    listSomeObj.Add(someObj);
    listSomeObj.Add(someObj2);
    listSomeObj.Add(someObj3);
}
public class Obj1
{
    public int id { get; set; }
    public string name { get; set; }
    public int age { get; set; }
}

//Here's your function to get that particular value    
public List<int> GetAgeList(List<Obj1> list)
{
    List<int> ageList = new List<int>();
    foreach (Obj1 obj in list)
    {
        ageList.Add(obj.age);
    }
    return ageList;
}

This is just an example.

Upvotes: 1

David Fox
David Fox

Reputation: 10753

Mannimarco is right--you should have provided some of what you have attempted :) There are a number of ways to do this. Maybe you should look up List (particularly, the extension method section) and start learning LINQ.

Use .Select() extension method of the Generic List type. (I'm assuming obj1 is the same type as Obj1 and you just made a typo)

public List<int> GetAgeList(List<Obj1> list)
{
    return list.Select(o => o.age).ToList();
}

Upvotes: 2

Related Questions