List <T> from property in List <T>

I could not learn much about how to do this. I probably do not believe the terminology.

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 to get a list of strings from the Name property so that it looks like this:

 { "Felix", "Fluffy" } 
+4
source share
10 answers
 var names = cats.Select(c => c.Name); 

But if you still need a list,

 List<string> names = cats.ConvertAll(c => c.Name); 
+5
source

LINQ Select operator - your friend:

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

I use ToList() to avoid lazy evaluation and ensure IList works.

+9
source

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

+2
source
 cats.Select(cat => cat.Name).ToList(); 

or

 (from cat in cats select cat.Name).ToList(); 

If you really don't need List as output, you can leave .ToList()

+2
source

If you are not allowed (or not needed) to use var, extension methods and Linq, or you need a list of strings:

 List<string> names = cats.ConvertAll(cat => cat.Name); 
+1
source
 var names = (from cat in cats select cat.Name).ToList(); 
0
source

using linq:

 var names = cats.Select(x => x.Name).ToList(); 
0
source
 var listOfNames = (from c in cats select c.Name).ToList(); 
0
source

Try the following:

 cats.Select(e => e.Name).ToArray(); 

Im pretty new with LINQ, so I cannot guarantee that this works.

Also, add the System.Linq namespace:

 using System.Linq; 
0
source
 cats.Select(cat => cat.Name).ToList() 
0
source

All Articles