Sam Hajari
Sam Hajari

Reputation: 354

Linq Groupby multiple columns with the same name (An anonymous type cannot have multiple properties with the same name)

I have an array of objects each object has 3 clients, each client has a client code and a client name. I want to use C# Linq to group by client code for different objects.

object[0]: client "pickupFrom" has "clientCode" client "loadAt" has "clientCode" client "deliverTo" has "clientCode"

object[1]: client "pickupFrom" has "clientCode" client "loadAt" has "clientCode" client "deliverTo" has "clientCode"

I want to group by those clients and get an array that has one object since those clients are identical.

using Linq I could do:

Objects[] GroupedDistinct = 
       ungroupedObjects.GroupBy(line => new { line.pickupFrom.clientCode,
                                              line.LoadAt.clientCode,
                                              line.deliverTo.clientCode })
                       .Select(x => x.First())
                       .ToArray();

The problem here is that when passing those parameters to groupby, I can't pass clientCode more than once since it is defining a string with the name clientCode more than once even though it does not come from the same client object.

the error is "An anonymous type cannot have multiple properties with the same name" I understand that you can't pass the same string name more than once but that is how those objects (clients) are done with clientCode. Is there a way around this?

Upvotes: 3

Views: 3338

Answers (1)

juharr
juharr

Reputation: 32296

Just give them unique names. Also I think you meant to use line and not object.

Objects[] GroupedDistinct = ungroupedObjects
    .GroupBy(line => new { 
        PickFromClientCode = line.pickupFrom.clientCode,
        LoadAtClientCode = line.LoadAt.clientCode,
        DeliverToClientCode = line.deliverTo.clientCode })
    .Select(x => x.First())
    .ToArray();

Upvotes: 10

Related Questions