简体   繁体   English

Linq Groupby具有相同名称的多个列(匿名类型不能具有具有相同名称的多个属性)

[英]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. 我有一个对象数组,每个对象有3个客户端,每个客户端都有一个客户端代码和一个客户端名称。 I want to use C# Linq to group by client code for different objects. 我想使用C#Linq按客户端代码对不同对象进行分组。

object[0]: client "pickupFrom" has "clientCode" client "loadAt" has "clientCode" client "deliverTo" has "clientCode" 对象[0]:客户端“ pickupFrom”具有“ clientCode”客户端“ loadAt”具有“ clientCode”客户端“ deliverTo”具有“ clientCode”

object[1]: client "pickupFrom" has "clientCode" client "loadAt" has "clientCode" client "deliverTo" has "clientCode" object [1]:客户端“ pickupFrom”具有“ clientCode”客户端“ loadAt”具有“ clientCode”客户端“ deliverTo”具有“ 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: 使用Linq我可以做到:

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. 这里的问题是,当将这些参数传递给groupby时,我不能多次传递clientCode,因为它多次定义了名称为clientCode的字符串,即使它不是来自同一客户端对象。

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. 错误是“匿名类型不能具有相同名称的多个属性”,我理解您不能多次传递相同的字符串名称,但这就是使用clientCode完成这些对象(客户端)的方式。 Is there a way around this? 有没有解决的办法?

Just give them unique names. 只是给他们唯一的名字。 Also I think you meant to use line and not object . 另外,我认为您打算使用line而不是object

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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