Generate a list of strings from a list of objects

I have a list of objects. I am interested in extracting one property of each object, a string value, into a list of strings. How can I create a list of strings using this field, preferably using Linq rather than manually?

class MyObj
{
  int ID {get;set;}
  int AnotherID (get;set;}
  string IneedThis {get;set;}
}

List<MyObj> sampleList = somehow_this_is_populated();
List<string> ls = how do I get this list with values equal to "sampleList.IneedThis"

      

+3


source to share


3 answers


You can Select

your property and create a list like:

List<string> ls = sampleList.Select(item => item.IneedThis).ToList();

      

Make sure you enable using System.Linq;

You can also achieve the same with a loop foreach

, for example:



List<string> ls = new List<string>();
foreach (MyObj myObj in sampleList)
{
    ls.Add(myObj.IneedThis);
}

      

Make sure that your properties are in class public

. In the current class, you do not have an access modifier and will count private

. Define them as:

public string IneedThis { get; set; }

      

+3


source


You can try this:



List<string> ls = sampleList.Select(x=>x.IneedThis).ToList();

      

+1


source


Use LINQ.

List<string> ls = sampleList.Select(obj => obj.IneedThis).ToList();

      

+1


source







All Articles