当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - grouping and counting objects based on property

问题描述:

I need to iterate a collection of objects. Based on a property value of the object, I need to group objects together. I also need a total count of each discrete property value. I do not know how many groups there will be and there could be 1 to n objects in each group.

How do I do this? Are there algortihms that could help me out with this? Psuedocode or references are fine.

Thanks much!

网友答案:

Look at 101 LINQ Samples - concrete at Group By Sample.

网友答案:

Here's some code that might help you. It groups the Target instances into groups by the property A and then iterates over the grouping and prints counts of the groups ...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IterateCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            var lst = new List<Target>() { new Target() { A=1, B=1 },
                                           new Target() { A=1, B=2 },
                                           new Target() { A=2, B=1 },
                                           new Target() { A=2, B=2 },
                                           new Target() { A=3, B=1 } };

            var grp = lst.GroupBy(t => t.A);
            var dic = grp.ToDictionary(g => g.Key);

            List<int> res = null;

            foreach (var key in dic.Keys )
            {
                res = dic[key].Select(t => t.A).ToList();

                Console.WriteLine("Number of {0} is {1}", key, res.Count);
            }


            Console.ReadLine();
        }
    }

    public class Target
    {
        public int A { get; set; }
        public int B { get; set; }
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: