Using LINQ, how to create a list of one specific field of an object from collection objects

If I have the following collection

IEnumerable<ProviderOrganisation> listOfProviders

public class ProviderOrganisation
{
    public virtual string Code { get; set; }
    public virtual string Description { get; set; }
    public virtual int SortOrder { get; set; }
    public virtual bool IsDefault { get; set; }
    public virtual DateTime EffectiveStartDate { get; set; }
    public virtual DateTime? EffectiveEndDate { get; set; }
}

How to write LINQ to create a collection of only codes, please?

So just a list of codes:

List<string> listOfCodes

thank

+3
source share
4 answers

Use Enumerable.Selectand Enumerable.ToList.

List<String> listOfCodes = listOfProviders
                     .Select(p => p.Code)
                     .ToList();
+3
source

You can call a method Select()to pull only the required property. Then call ToList()to execute it.

listOfProviders.Select(p => p.Code).ToList();
+2
source

In the query syntax, it will look like this:

List<string> listOfCodes = (from p in listOfProviders
                            select p.code).ToList();
0
source

I like to use ConvertAll

List<string> listOfCodes = listOfProviders
                    .ToList()
                    .ConvertAll(x => x.Code);

And a little testing shows that ConvertAll is always a little faster than the current accepted answer method! :)

0
source

All Articles