Tuesday, February 12, 2013

LINQ GroupBy Count

class Program

    {

        static void Main(string[] args)

        {

            var employeeProducts = new List<EmployeeProduct>();

            employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));

            employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));

            employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));

 

            var way1 = employeeProducts.Select(

                ep => new ProductCount

                {

                    ProductNumber = ep.ProductID,

                    EmployeeNumber = ep.EmployeeID,

                    CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)

                });

 

            var way2 = employeeProducts

                .GroupBy(ep => ep.ProductID)

                .SelectMany(epg => epg.Select(

                    ep => new ProductCount

                    {

                        ProductNumber = ep.ProductID,

                        EmployeeNumber = ep.EmployeeID,

                        CountProducts = epg.Count()

                    }));

        }

 

        public class EmployeeProduct

        {

            public EmployeeProduct(int employeeID, int productID, string name)

            {

                EmployeeID = employeeID;

                ProductID = productID;

                Name = name;

 

            }

            public int EmployeeID { get; set; }

            public int ProductID { get; set; }

            public string Name { get; set; }

        }

 

        public class ProductCount

        {

            public int ProductNumber { get; set; }

            public int EmployeeNumber { get; set; }

            public int CountProducts { get; set; }

        }

    }

No comments:

Post a Comment