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

后端 未结 4 1028
名媛妹妹
名媛妹妹 2020-12-07 13:42

Say I have the following class:

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


        
相关标签:
4条回答
  • 2020-12-07 14:03

    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.

    0 讨论(0)
  • 2020-12-07 14:21

    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.

    0 讨论(0)
  • 2020-12-07 14:21

    This should also work:

    AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
    
    0 讨论(0)
  • 2020-12-07 14:27

    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.

    0 讨论(0)
提交回复
热议问题