Search code examples
c#listenumerable

For each item in list of classes


I'm fairly sure this question has been asked before, but I'm unsure what to search for, so if there is something already been asked for this, please direct me there.

Usually, I would do something like this

List<string> values = new List<string>();
foreach (MyClass workingClass in AllTheClasses)
{
    string val = workingClass.SomeField);
    values.Add(val);
}

However, I would like to use something like this :

List<string> values = AllTheClasses.ToList(SomeField);

Is there a better way to do this?


Solution

  • Linq the way:

    var values = AllTheClasses.Select(c=>c.SomeField).ToList();