LINQ - 对具有类型计数的对象进行分组

时间:2011-07-12 06:08:30

标签: linq grouping aggregate

我有一组对象,每个对象都由一个特定的“组”定义。如何编写LINQ查询以生成按“组”分组的每个对象的计数。

举个例子,假设我有以下类;

public class Release 
{
     int ReleaseNumber; 

     public ReleaseDetails[] details;

}

public class ReleaseDetails
{
    string Group;

    // other details omitted
}

对于给定的版本,我希望能够生成类似的输出

Release number 1 contains the following details;
 - 17 records in Group A
 - 12 records in Group B
 - 6 records in Group C

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以执行类似

的操作
var q = from d in r.Details
            group d by d.Group into counts
            select new { Count = counts.Count(), Group = counts.Key };

完整示例:

        Release r = new Release
        {
            ReleaseNumber = 1
            ,
            Details = new ReleaseDetails[]
            {
                new ReleaseDetails { Group = "a"},
                new ReleaseDetails { Group = "a"},
                new ReleaseDetails { Group = "b"},
                new ReleaseDetails { Group = "c"},
                new ReleaseDetails { Group = "d"},
                new ReleaseDetails { Group = "d"},
                new ReleaseDetails { Group = "e"},

            }
        };

        var q = from d in r.Details
                group d by d.Group into counts
                select new { Count = counts.Count(), Group = counts.Key };

        foreach (var count in q)
        {
            Console.WriteLine("Group {0}: {1}", count.Group, count.Count);
        }

答案 1 :(得分:1)

你走了。

    public class ReleaseDetails
    {
        public string Group { get; set; }
        public ReleaseDetails() {}
        public ReleaseDetails(string grp){Group = grp;}
    }

            var qry = new Release();
            qry.details = new List<ReleaseDetails>();
            qry.details.Add(new ReleaseDetails("A"));
            qry.details.Add(new ReleaseDetails("A"));
            qry.details.Add(new ReleaseDetails("B"));
            qry.details.Add(new ReleaseDetails("C"));
            qry.details.Add(new ReleaseDetails("C"));
            qry.details.Add(new ReleaseDetails("B"));


 var result = from x in qry.details
                group x by x.Group into g
                select new 
                { 
                    Count = g.Count(), 
                    Group = g.Key 
                };

//Or using Labmda
var result1 = qry.details.GroupBy(x => x.Group).Select(g => new { Count = g.Count(), Group = g.Key });