1

大家好,我的 GroupBy 查询有什么问题?

我有以下课程:

public class AssembledPartsDTO
{
    public int PID { get; set; }
    public McPosition Posiotion { get; set; }
    public string Partnumber { get; set; }
    public string ReelID { get; set; }
    public int BlockId { get; set; }
    public List<string> References { get; set; }
}

我正在尝试执行以下查询:

assembledPcb.AssembledParts.GroupBy(entry => new
                        {
                            entry.PID,
                            entry.Posiotion.Station,
                            entry.Posiotion.Slot,
                            entry.Posiotion.Subslot,
                            entry.Partnumber,
                            entry.ReelID,
                            entry.BlockId
                        }).
                        Select( (key , val )=> new AssembledPartsDTO
                            {
                                BlockId = key.Key.BlockId,
                                PID = key.Key.PID,
                                Partnumber = key.Key.Partnumber,
                                ReelID = key.Key.ReelID,
                                Posiotion = new McPosition(key.Key.Station, key.Key.Slot, key.Key.Subslot),
                                References = val <-- ????
                            })

但是val 我有的是类型int而不是分组的值,我可以在那里做val.SelectMany(v => v).ToList();任何想法我的代码有什么问题?

4

1 回答 1

5

的第二个参数Enumerable.Select是该项目在序列中的索引。所以在这种情况下,它是组的(从零开始的)数字。您只想选择组,不需要它的索引:

var result = assembledPcb.AssembledParts.GroupBy(entry => new
{
    entry.PID,
    entry.Posiotion.Station,
    entry.Posiotion.Slot,
    entry.Posiotion.Subslot,
    entry.Partnumber,
    entry.ReelID,
    entry.BlockId
})
.Select(g => new AssembledPartsDTO
{
    BlockId = g.Key.BlockId,
    PID = g.Key.PID,
    Partnumber = g.Key.Partnumber,
    ReelID = g.Key.ReelID,
    Posiotion = new McPosition(g.Key.Station, g.Key.Slot, g.Key.Subslot),
    References = g.SelectMany(entry => entry.References)
                  .Distinct()
                  .ToList()
});

(假设你想要一个不同的引用列表)

旁注:您的属性名称有错字:Posiotion

于 2013-05-27T12:31:24.100 回答