Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate list of string from list of objects [duplicate]

Tags:

c#

.net

linq

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"
like image 486
NoBullMan Avatar asked Dec 09 '14 15:12

NoBullMan


People also ask

How to convert list of integer to list of string in Java?

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.

What is the use of list in Java?

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.

How to create a list of all properties in a class?

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.

How to convert list to list in Java 8 stream?

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.


3 Answers

You could try this one:

List<string> ls = sampleList.Select(x=>x.IneedThis).ToList();
like image 44
Christos Avatar answered Nov 11 '22 05:11

Christos


Use LINQ.

List<string> ls = sampleList.Select(obj => obj.IneedThis).ToList();
like image 21
Tim Schmelter Avatar answered Nov 11 '22 04:11

Tim Schmelter


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; }
like image 74
Habib Avatar answered Nov 11 '22 03:11

Habib