Trevor Daniel
Trevor Daniel

Reputation: 3974

LINQ Cannot implicitly convert type Generic.ICollection to Generic.List

I have been thrown in the deep end with some software and it involves LINQ, which I am having problems with.

Background:

I need to display a list of payments relating to an organisation.

I have pulled the organisation object out of the database like this:

var orgDetails = Ctx.Organizations.Where(x => x.OrganizationId == orgID);

I have then pulled out the payments like this:

var orgPayments = (from payments in orgDetails.Select(x => x.ProcessedPayments) select payments);

Then I want to pass them into a class:

public class InvoiceDetails
{
    public List<ProcessedPayment> ProcessedPayment { get; set; }
    public List<InvoiceLineItems> InvoiceLineItems { get; set; }
}

like this:

InvoiceDetails InvoiceDetailModel = new InvoiceDetails
{
    ProcessedPayment = orgPayments,
    InvoiceLineItems = invoicelineitems
};

And I get the dreaded error:

LINQ Cannot implicitly convert type Generic.ICollection to Generic.List

I just cannot work out what I need to do to cast it to a list. I have tried changing it to

var orgPayments = (from payments in orgDetails.Select(x => x.ProcessedPayments) select payments).ToList();

With no luck

Can anyone help me find out what I am doing wrong?

Thanks

Upvotes: 1

Views: 1742

Answers (1)

DavidG
DavidG

Reputation: 119156

Your first query gives you a list of organisations rather than a single one which I believe is what you are looking for (assuming OrganizationId is your primary key.) Look at the Where method, it returns an IEnumerable<>.

So I would change it to:

var orgDetails = organizations.Single(x => x.OrganizationId == orgID);

Be aware that this will throw an exception if an organisation with orgID is not found so you may need to use SingleOrDefault instead and check that orgDetails != null.

Which means you don't need any further linq to get the payments and instead of creating the orgPayments variable, just use orgDetails.ProcessedPayments like this:

InvoiceDetails InvoiceDetailModel = new InvoiceDetails
{
    ProcessedPayment = orgDetails.ProcessedPayments,
    InvoiceLineItems = invoicelineitems
};

Upvotes: 3

Related Questions