Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 255
edan Avatar asked Sep 01 '10 23:09

edan


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Full form of C is “COMPILE”.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

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);
like image 130
LukeH Avatar answered Oct 06 '22 02:10

LukeH


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);
}
like image 22
Ahmad Mageed Avatar answered Oct 06 '22 03:10

Ahmad Mageed