views:

74

answers:

3

Hi, 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!!

+8  A: 

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);
}
Ahmad Mageed
It might be worth mentioning that if all you want to do is iterate over it, you don’t need `ToList()`. Use that only if you need to modify the new list or index into it.
Timwi
+1  A: 

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();
Dan Tao
A: 

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);
LukeH
well, in my case, the input and output are not the same. input is List<MyObject> and output is List<string>. will convertAll() still work?
edan
What is “there is no need for LINQ” supposed to mean? It’s not like LINQ is a whole separate library or anything, you know. Whether you use `.ConvertAll` or `.Select` makes no practical difference.
Timwi
@edan: Yes, `ConvertAll` will work, as in my example above.
LukeH
@Timwi: It means exactly what it says: using LINQ isn't the only possible solution; `ConvertAll` is another alternative. In fact, `ConvertAll` will be slightly more efficient than LINQ because *(a)* it can copy the data using direct array access rather than needing to instantiate and repeatedly call iterators, and *(b)* it can allocate the destination list to the correct size at the outset rather than dynamically resizing as it goes. (But, as you say, this small performance benefit makes no practical difference in *most* real-world situations.)
LukeH