Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ how do I create a List of one particular field of an entity from a collection entities

Tags:

c#

list

lambda

linq

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 do I write the LINQ to produce a collection of just Codes please?

So, just a List of the Codes:

List<string> listOfCodes

Thanks

like image 759
Stu Harper Avatar asked Oct 28 '25 13:10

Stu Harper


2 Answers

Use Enumerable.Select and Enumerable.ToList.

List<String> listOfCodes = listOfProviders
                     .Select(p => p.Code)
                     .ToList();
like image 106
Tim Schmelter Avatar answered Oct 31 '25 11:10

Tim Schmelter


You can call the Select() method to pull out only the property you need. Then call ToList() to cast it.

listOfProviders.Select(p => p.Code).ToList();
like image 24
hunter Avatar answered Oct 31 '25 12:10

hunter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!