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

C#Linq

C# Problem Overview


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).

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

>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).

Yes, LINQ can do this. It's simply:

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

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.

Solution 3 - C#

This should also work:

AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())

Solution 4 - C#

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVaccanoView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#jasonView Answer on Stackoverflow
Solution 3 - C#Shadow Wizard Says No More WarView Answer on Stackoverflow
Solution 4 - C#SpyrosView Answer on Stackoverflow