c# getting a list from a field out of a list
I'm sorry about the confusing title, but I didnt find a better way to explain my issue.
I have a list of objects, myList
, lets call them MyObject
. the objects look something like this:
Class MyObject
{
int MYInt{get;set;}
string MYString{get;set;}
}
List<MyObject> myList;
...
I am开发者_如何学编程 looking for a nice/short/fancy way to create a List<string>
from myList
, where I am using only the MyString
property.
I can do this using myList.forEach()
, but I was wondering if there's a nicer way
Thanks!!
With LINQ:
var list = myList.Select(o => o.MYString);
That returns an IEnumerable<string>
. To get a List<string>
simply add a call to ToList()
:
var list = myList.Select(o => o.MYString).ToList();
Then iterate over the results as you normally would:
foreach (string s in list)
{
Console.WriteLine(s);
}
There's no need for LINQ if your input and output lists are both List<T>
. You can use the ConvertAll
method instead:
List<string> listOfStrings = myList.ConvertAll(o => o.MYString);
Here's Ahmad's answer using integrated query syntax:
var strings = from x in myList
select x.MYString;
List<string> list = strings.ToList();
This could also be written:
List<string> list = (from x in myList
select x.MYString).ToList();
精彩评论