List<T> from property in List<T>
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 开发者_C百科property so it looks like this:
{ "Felix", "Fluffy" }
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.
var names = cats.Select(c => c.Name);
But if you still need a list use
List<string> names = cats.ConvertAll(c => c.Name);
cats.Select(x => x.Name).ToList()
cats.Select(cat => cat.Name).ToList();
or
(from cat in cats select cat.Name).ToList();
If you don't actually need the List
as an output, you can leave off the .ToList()
If you're not allowed (or don't want to) use var, extension methods and Linq or need a list of strings:
List<string> names = cats.ConvertAll(cat => cat.Name);
using linq:
var names = cats.Select(x => x.Name).ToList();
var listOfNames = (from c in cats
select c.Name).ToList();
Try this:
cats.Select(e => e.Name).ToArray();
Im pretty new with LINQ so I dont guarntee that works.
Also, add System.Linq namespace:
using System.Linq;
cats.Select(cat => cat.Name).ToList()
var names = (from cat in cats
select cat.Name).ToList();
精彩评论