2014-10-06 232 views
1

使用LINQ,如何將此列表結果分組爲firstThree?我的組方法不起作用。LINQ - GROUP BY IEnumerable

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); 


     } 
+2

的呼叫都爲'ToList'在你的代碼完成什麼。您根本不需要使用該方法來執行此查詢。 – Servy 2014-10-06 19:48:45

回答

2

您的GroupBy不工作的原因是您忽略了其結果。它應該是這樣的:

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

更改foreach循環這樣完成修復:

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

您的解決方案幫助我完成了所需的分組,非常感謝您的先生。 – user2751629 2014-10-07 12:55:12