4

我正在向 a 添加一堆不同的零件,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);
    }

}
4

2 回答 2

10

我猜你想创建一堆组对象,其中每个组对象都有共同的和具有该长度Length的一堆s。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具有该长度的 s 的集合。

如果你调用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()
  ;
}
于 2013-04-07T17:06:41.637 回答
0

您正在尝试转换IEnumerable<IGrouping<int ICutPart>><IGrouping<int ICutPart>>`; 这永远不会奏效。您必须从 IEnumerable<> 中选择一个实例,可能像这样:

return sGroup.FirstOrDefault();
于 2013-04-07T17:06:32.210 回答