开发者

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!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜