Home > OS >  How to get Max count and Min Count from List of Object using Linq
How to get Max count and Min Count from List of Object using Linq

Time:09-10

I need to group it based on month and get the Max and Min counts. Hear, Sep Month has Max count and Jun Month has Min count. So I need max value as 5 and Min value as 1.

Thanks in advance.

public class Test
            {
            public string Month { get; set; }
            public string ID { get; set; }
            public string SubMonth { get; set; }

            }

            List<Test> test = new List<Test>();

            test.Add(new Test { Month = "Sep", ID ="1",  SubMonth = "Sep2" });
            test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep3" });
            test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep4" });
            test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep5" });
            test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep6" });

            test.Add(new Test { Month = "Jun", ID = "3", SubMonth = "Jun2" });


            test.Add(new Test { Month = "Jul", ID = "4", SubMonth = "Jul2" });
            test.Add(new Test { Month = "Jul", ID = "4", SubMonth = "Jul3" });

            test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan2" });
            test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan3" });
            test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan4" });
            test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan5" });

CodePudding user response:

You can do in this way. You will get max and min count:

var result = (test.GroupBy(item => item.Month)
                        .Select(itemGroup => new { Item = itemGroup.Key, Count = itemGroup.Count() })
                        .OrderByDescending(Item => Item.Count).ThenBy(Item => Item.Item)
                     ).ToList(); 
        Console.WriteLine("{0} {1}\r\n{2} {3}", result.First().Item, result.First().Count, result.Last().Item, result.Last().Count);

CodePudding user response:

Using linq you can do it in this way.

var sepCount = test.Where(x => x.Month == "Sep").Count();
var junCount = test.Where(x => x.Month == "Jun").Count();
// you can get the count of each month in the list
var monthCount = test.GroupBy(x => x.Month).ToList().Select(x => x.Count()).ToList();
  • Related