Search code examples
c#linqpartitionrow-number

Linq group by and select most occuring item in sub group


I have been struggling to write a linq query in c# for this scenario below, I have got a list with the structure

PostCode, Premise, Connectivity, Availability
XYZ 123,    1,       HIGH,         TRUE
XYZ 123,    2,       LOW,          TRUE
XYZ 123,    3,       LOW,          FALSE
ABC 234,    1,       HIGH,         FALSE
ABC 123,    2,       HIGH,         FALSE

I am trying to generate the below which I have done in SQL using ROW_NUMBER and partition but it's a challenge for me to achieve in c#. Any help is highly appreciated.

PostCode,  Connectivity, Availability
XYZ 123,         LOW,          TRUE
ABC 234,         HIGH,         FALSE

Solution

  • It this what you are looking for :

    class Program
    {
        static void Main(string[] args)
        {
            List<PostCode> postCodes = new List<PostCode>() {
                new PostCode() {postcode = "XYZ 123", premise = 1, connectivity = "HIGH", availability = "TRUE"},
                    new PostCode() {postcode = "XYZ 123", premise = 2, connectivity = "LOW", availability = "TRUE"},
                    new PostCode() {postcode = "XYZ 123", premise = 3, connectivity = "LOW", availability = "FALSE"},
                    new PostCode() {postcode = "ABC 234", premise = 1, connectivity = "HIGH", availability = "FALSE"},
                    new PostCode() {postcode = "ABC 123", premise = 2, connectivity = "HIGH", availability = "FALSE"}
                };
    
                var results = postCodes.GroupBy(x => x.postcode)
                    .Select(x => x.GroupBy(y => y.premise).Select(z => new { item = z, count = z.Count() }).ToList())
                    .ToList();
            }
        }
        public class PostCode
        {
            public string postcode {get; set;}
            public int premise { get; set; }
            public string connectivity { get; set; }
            public string availability { get; set; }
    
        }