Assume the following class:
class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
Lets say that I have a list or an array of Person object. Is there a way using LINQ to retrieve FirstName property from all the array elements and return an array of string. I have a feeling that I have seen something like that before.
Hope that the question makes sense.
At which point you can access it by simply saying newJsonArray[i]. Code or whatever property inside the array you want to use.
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop.
To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.
Sure, very easily:
Person[] people = ...;
string[] names = people.Select(x => x.FirstName).ToArray();
Unless you really need the result to be an array though, I'd consider using ToList()
instead of ToArray()
, and potentially just leaving it as a lazily-evaluated IEnumerable<string>
(i.e. just call Select
). It depends what you're going to do with the results.
If you have an array, then personally, I'd use:
Person[] people = ...
string[] names = Array.ConvertAll(people, person => person.FirstName);
here; it avoids a few reallocations, and works on more versions of .NET. Likewise:
List<Person> people = ...
List<string> names = people.ConvertAll(person => person.FirstName);
LINQ will work, but isn't actually required here.
Try this:
List<Person> people = new List<Person>();
people.Add(new Person()
{
FirstName = "Brandon",
LastName = "Zeider"
});
people.Add(new Person()
{
FirstName = "John",
LastName = "Doe"
});
var firstNameArray = people.Select(p => p.FirstName).ToArray();
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