Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of properties from List of objects

Tags:

c#

Currently I use foreach loop to return a list of object properties.

 class X  {      List<X> Z = GetXlist();      List<String> r = new List<String>();       foreach (var z in Z)      {          r.Add(z.A);      }       return r; } 

Is there a way that I can shorten this so that I don't have to write the foreach loop?

like image 731
user1615362 Avatar asked Dec 08 '12 20:12

user1615362


People also ask

How can you get the list of all properties in an object?

To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.

Can we have list of objects?

Yes, it is absolutely fine to have an object contains list of object.

What are object properties in JavaScript?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.


1 Answers

LINQ is the answer. You can use it to "project" from your object collection to another collection - in this case a collection of object property values.

List<string> properties = objectList.Select(o => o.StringProperty).ToList(); 
like image 125
Honza Brestan Avatar answered Oct 01 '22 03:10

Honza Brestan