Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of objects to an array of one of the object's properties

Tags:

c#

linq

Say I have the following class:

public class ConfigItemType {     public string Name { get; set; }     public double SomeOtherThing { get; set; } } 

and then I make a list of the following classes (List<ConfigItemType> MyList)

Now I have a method with the following signature:

void AggregateValues(string someUnrelatedValue, params string[] listGoesHere) 

How can I fit MyList in to the listGoesHere using the value in ConfigItemType.Name as the params string array?

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

like image 956
Vaccano Avatar asked Jan 21 '11 23:01

Vaccano


People also ask

How do you convert a list of objects into an object?

The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.

How do you change one property in an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is.


1 Answers

You are looking for

MyList.Select(x=>x.Name).ToArray(); 

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.

like image 53
BrokenGlass Avatar answered Sep 17 '22 15:09

BrokenGlass