Fil*_* DO 4 .net c# linq windows group-by
我在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);
}
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ler 10
我想你想要创建一组组对象,其中每个组对象具有公共Length
和ICutPart
具有该长度的一堆s.
在代码中,它看起来像这样:
public IEnumerable<IGrouping<int, ICutPart>> GroupParts()
{
return this.GroupBy( o => o.Length );
}
Run Code Online (Sandbox Code Playgroud)
那可能需要解释!
该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; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以返回这些对象的集合:
public List<GroupedByLength> GroupParts()
{
return this
.GroupBy( o => o.Length )
.Select( g => new GroupedByLength
{
Length = g.Key,
CutParts = g.ToList(),
}
)
.ToList()
;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6899 次 |
最近记录: |