如何从 Linq 查询中返回 IGrouping 分组结果

4
我正在向 List<> 添加许多不同的部件,有些部件可能具有相同的零件号和相同的长度。如果它们具有相同的零件号和相同的长度,则需要将这些部件分组以进行显示。
当它们被分组时,我需要显示该零件号以及具有特定长度的该零件号的数量。
我需要知道如何使用两个不同的属性进行分组,并返回具有List<ICutPart> 和总数的类型化对象。
以下是我能够做到的,我尝试返回(IGrouping<int,ICutPart>)sGroup;,但我在函数体的返回部分遇到错误。
我该如何返回具有Group{List<ICutPart> Parts, Int Total} 的类型化对象?
    public class CutPart : ICutPart
{
    public CutPart() { }
    public CutPart(string name, int compID, int partID, string partNum, decimal length)
    {
        this.Name = name;
        this.PartID = partID;
        this.PartNumber = partNum;
        this.CompID = compID;
        this.Length = length;
    }
    public CutPart(string name, int compID, int partID, string partNum, decimal width, decimal height)
    {
        this.Name = name;
        this.CompID = compID;
        this.PartNumber = partNum;
        this.PartID = partID;
        this.Width = width;
        this.Height = height;
        this.SF = decimal.Parse(((width / 12) * (height / 12)).ToString(".0000")); //2dp Number;
    }

    public string Name { get; set; }
    public int PartID { get; set; }
    public string PartNumber { get; set; }
    public int CompID { get; set; }
    public decimal Length { get; set; }
    public decimal Width { get; set; }
    public decimal Height { get; set; }
    public decimal SF { get; set; }
}

public class CutParts : List<ICutPart>
{

    public IGrouping<int, ICutPart> GroupParts()
    {

        var sGroup = from cp in this
                     group cp by cp.Length into g
                     select new
                     {
                         CutParts = g,
                         total = g.Count() 
                     };

        return (IGrouping<int, ICutPart>)sGroup;

    }


    public new void Add(ICutPart item)
    {
        base.Add(item);
    }

}
2个回答

10

我猜你想创建一堆组对象,每个组对象都有共同的Length和拥有该长度的一堆ICutPart

在代码中,它看起来像这样:

public IEnumerable<IGrouping<int, ICutPart>> GroupParts()
{
  return this.GroupBy( o => o.Length );
}

那可能需要解释一下!


IEnumerable 部分是一组对象的集合 - 每个不同的 Length 对应一个组对象。

该集合中的每个“组对象”都是一个 IGrouping<int, ICutPart>

此对象具有一个 Key 属性,它是您进行分组的内容 - 在这种情况下是 Length

它也是一个集合,因为 IGrouping<T> 派生自 IEnumerable<T> - 它是具有该长度的 ICutPart 的集合。

如果在其中一个组对象上调用 ToList(),则会获得一个 List<ICutPart>


为了方便调用者,您可以创建一个类来保存这些值。

如果您声明了一个如下所示的类:

public class GroupedByLength
{
  public int Length { get; set; }
  public List<ICutPart> CutParts { get; set; }
}

然后您可以返回这些对象的集合:

public List<GroupedByLength> GroupParts()
{
  return this
    .GroupBy( o => o.Length )
    .Select( g => new GroupedByLength
      {
        Length = g.Key,
        CutParts = g.ToList(),
      }
    )
    .ToList()
  ;
}

0

您正在尝试将 IEnumerable<IGrouping<int ICutPart>> 强制转换为 <IGrouping<int ICutPart>>,这是不可能的。您需要从 IEnumerable<> 中选择一个实例,例如:

return sGroup.FirstOrDefault();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接