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"
source to share
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; }
source to share