Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> from property in List<T>

Tags:

c#

generics

I wasn't able to find much about how to do this. I'm probably not getting the terminology right.

I have a list of objects:

class Cat()
{
   public string Name { get; set; }
}

List<Cat> cats = new List<Cat>();

cats.add(new Cat() { Name = "Felix" } );
cats.add(new Cat() { Name = "Fluffy" } );

How do I get a list of strings from the Name property so it looks like this:

{ "Felix", "Fluffy" }
like image 252
Levitikon Avatar asked Dec 01 '22 01:12

Levitikon


2 Answers

The LINQ Select operator is your friend:

cats.Select(c => c.Name).ToList()

I am using ToList() to avoid lazy evaluation and to ensure you have an IList to work with.

like image 138
Oded Avatar answered Dec 04 '22 22:12

Oded


var names = cats.Select(c => c.Name);

But if you still need a list use

List<string> names = cats.ConvertAll(c => c.Name);
like image 38
Yuriy Faktorovich Avatar answered Dec 04 '22 22:12

Yuriy Faktorovich