我正在向 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);
}
}
最佳答案
我猜你想创建一堆组对象,其中每个组对象都有共同的 Length
和一堆ICutPart
具有该长度的 s。
在代码中,它看起来像这样:
public IEnumerable<IGrouping<int, ICutPart>> GroupParts()
{
return this.GroupBy( o => o.Length );
}
这可能需要解释一下!
IEnumerable
bit 是组对象的集合 - 每个不同的 Length
该集合中的每个“组对象”都是一个 IGrouping<int, ICutPart>
.
这个对象有一个 Key
属性(property),这是你分组的东西 - 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()
;
}
关于c# - 分组时如何从 Linq 查询返回 IGrouping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15865030/