Anthony
Anthony

Reputation: 2824

Getting list of values out of list of objects

I have a simple class:

 private class Category
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }  

an also a list of objects of this type:

 List<Category> Categories;

I need to get a list of Ids that are in Categories list. Is there a simpler way to do this than using for loop like this:

 List<int> list = new List<int>();
    for (int i = 0; i < Categories.Count; i++)
    {
        list.Add(Categories[i].Id);
    }

Thanks in advance.

Upvotes: 39

Views: 106434

Answers (3)

David Meshak
David Meshak

Reputation: 71

Categories.Select(c => c.Id).ToList();

Gives a list of lists (List<List<Id>>).

Categories.SelectMany(c => c.Id).ToList();

Returns only a list of Ids.

Upvotes: 2

Display Name
Display Name

Reputation: 8128

This expression gives you the list you want:

    Categories.Select(c => c.Id).ToList();

Also, don't forget

    using System.Linq;

Upvotes: 103

Thilina H
Thilina H

Reputation: 5804

Use as follows.

Categories.Select(c => c.Id).ToList();

||

List<int> list = new List<int>();
foreach (Category item in Categories)
{
    list.Add(item.Id);
}  

Upvotes: 16

Related Questions