bradley32110
bradley32110

Reputation: 63

LINQ - GROUP BY IEnumerable

Using LINQ, how can I group this list results by firstThree? My group method is not working.

    var findOtherZipCodes = (from z in zipCodes                                    
                                 from results in zipFirstThree
                                 where (results.region.ToUpper() == z.City
                                 && results.state == z.State)   
                                select new ZipCodeFirstThree
                                {
                                    region = z.City,
                                    state = z.State,
                                    firstThree = z.ZipCode1.ToString().Substring(0, 3),
                                    zipCode = z.ZipCode1.ToString()
                                }).ToList();

   findOtherZipCodes.GroupBy(x => x.firstThree).ToList();

        foreach (var item in findOtherZipCodes) {
            Console.WriteLine(item.region + " " + item.firstThree + " " + item.zipCode);
            Thread.Sleep(500);


        }

Upvotes: 3

Views: 10540

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The reason your GroupBy is not working is that you are ignoring its results. It should be like this:

var groups = findOtherZipCodes.GroupBy(x => x.firstThree).ToList();

Change the foreach loop like this to complete the fix:

foreach (var group in groups) {
    var firstInGroup = group.First();    
    Console.WriteLine(firstInGroup.region + " " + group.Key + " " + firstInGroup.zipCode);
    Thread.Sleep(500);
}

Upvotes: 3

Related Questions