2013-04-07 92 views
3

我在List<>中添加了一堆不同的零件,其中一些零件可能具有相同的零件号和相同的长度。如果他们具有相同的零件编号和相同的长度,我需要将这些零件分组来显示。如何在分组时使用Linq查询返回IGrouping

当它们分组时,我需要显示该零件编号以及具有特定长度的零件编号的数量。

我需要知道如何在两个不同的充地产集团,并返回eaigher与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); 
    } 

} 

回答

9

我猜你想创建一堆,每个组对象有共同LengthICutPart S上的一堆对象组是有这个长度。

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

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() 
    ; 
} 
+0

谢谢尼古拉斯。 – 2013-04-07 17:15:37

+0

@ AlumCloud.Com不客气:) – 2013-04-07 17:21:23

0

您试图投IEnumerable<IGrouping<int ICutPart>><IGrouping<int ICutPart>>`;这将永远不会工作。你将不得不从IEnumerable的<选择instnace>,也许是这样的:

return sGroup.FirstOrDefault();