简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM