views:

51

answers:

2

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!

+2  A: 

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

TcKs
A: 

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; }
    }
}
JP Alioto