NorwegianClassic
NorwegianClassic

Reputation: 1115

How do I efficiently get the property as a list from IReadOnlyCollection?

I have a IReadOnlyCollection of a class called MyProducts looking like this:

[
    {
        "Id": 2987,
        "Name": Brick,

        ...
    },
    {
        "Id": 35246,
        "Name": Wood,

        ...
    },

...

]

How can I efficiently get the IDs as a list like this:

[
    "2987",
    "35246"
]  

I would prefer not to use a loop. Is there for example an inbuilt function that can help me out?

Upvotes: -1

Views: 317

Answers (3)

tina
tina

Reputation: 49

This solution does unfortunately not work for IReadOnlyCollection but for List<T>, so maybe it is useful for someone:

There is a way without Linq and without a loop

var productIds = MyProducts.ConvertAll(p => p.Id);

Upvotes: -1

Moo-Juice
Moo-Juice

Reputation: 38820

To supplement Tim's answer with a non-LINQ solution:

List<int> ids = new List<int>(products.Count);
for(int i = 0; i < products.Count; ++i)
    ids.Add(products[i].Id);

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460228

Just use LINQ:

List<int> idList = products.Select(p => p.Id).ToList();

That's not more efficient than a plain loop but it's shorter, so probably more readable.

Upvotes: 7

Related Questions