我的Group By Query有什么问题

时间:2013-05-27 12:23:25

标签: c# linq

大家好我的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();知道我的代码中有什么问题?

1 个答案:

答案 0 :(得分: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