I have a list of objects. I am interested in isolating one property of each object, a string value, into a list of strings. How can I create a list of strings using this field only, preferably using Linq and not manually looping?
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"
Convert List of Integer to List of String using Lists.transform (). This is done using passing s -> String.valueOf (s) method as lambda expression for transformation.
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
You can Select your property and create a List like: You can also achieve the same with a foreach loop like: Make sure that your properties in the class are public. In your current class then don't have a access modifier and will be considered private.
Java 8 Stream API can be used to convert List to List. Get the List of Integer. Convert List of Integer to Stream of Integer. This is done using List.stream (). Convert Stream of Integer to Stream of String. This is done using Stream.map () and passing s -> String.valueOf (s) method as lambda expression.
You could try this one:
List<string> ls = sampleList.Select(x=>x.IneedThis).ToList();
Use LINQ.
List<string> ls = sampleList.Select(obj => obj.IneedThis).ToList();
You can Select
your property and create a List like:
List<string> ls = sampleList.Select(item => item.IneedThis).ToList();
Make sure your include using System.Linq;
You can also achieve the same with a foreach
loop like:
List<string> ls = new List<string>();
foreach (MyObj myObj in sampleList)
{
ls.Add(myObj.IneedThis);
}
Make sure that your properties in the class are public
. In your current class then don't have a access modifier and will be considered private
. Define them like:
public string IneedThis { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With