2011-03-29 32 views
0

我有一個年齡從0到119歲的人口。使用VB.NET 2008進行分組的Linq代碼是什麼?

我想組這個人口從15歲到49根據下面的假設:

  1. 15至19;
  2. 20至24;
  3. 25至29;
  4. 30至34;
  5. 35至39;
  6. 40至44;
  7. 45至49

任何年齡除了這些無用的計算我需要執行。以下是一些示例數據和代碼。

我有一個AnnualPopulation類,它代表每個年齡段的人口統計人口。

Public Class AnnualPopulation 
    Public Id as Integer 
    Public Year As Integer 
    Public Gender As String 
    Public YearsOfAge As Double?() = New Double?(119) { } 
End Class 

然後,YearsOfAge數組/集合屬性包含基於其性別的人數。例如:

AnnualPopulation.Year = 2009 
AnnualPopulation.Gender = "F"c 
For age As Integer = 0 To AnnualPopulation.YearsOfAge.Length - 1 Step 1 
    YearsOfAge(age) = 42356.67F 'Of course, this number varies from a years of age to another!' 
Next 

我會那麼喜歡組如如下:

Dim groups() As Double = New Double(6) { } 
For age As Integer = 15 To 49 Step 1 
    Dim index As Integer = 0 

    Select Case age 
     Case 15 to 19 
      index = 0 
     Case 20 To 24 
      index = 1 
     Case 25 To 29 
      index = 2 
     Case 30 To 34 
      index = 3 
     Case 35 To 39 
      index = 4 
     Case 40 To 44 
      index = 5 
     Case 45 To 49 
      index = 6 
    End Select 

    groups(index) += AnnualPopulation.YearsOfAge(age - 1) 
Next 

這樣,我將不得不人口的總和的年齡一年的每個範圍

所以,我雖然分組他們,然後我沒有共同的關鍵將他們分組,沒有運氣! = P在C#中,我想這會做什麼,我需要:

double[] groups = new double[7]; 
Enumerable.Range(15, 34).ToList().ForEach(age => { 
    groups[(int)(age % 4)] += annualPopulation.YearsOfAge[age - 1].HasValue 
           ? annualPopulation.YearsOfAge[age - 1].Value : 0.0; 
}); 

似乎我不能夠在2008年VB.NET實現,除非我嘗試用New Action(Of T1, T2)否則Func(Of Double?, TKey)一起去。這些我都不舒服! =((基本問題:爲什麼它在VB.NET中如此複雜的工作與lambdas!?

我的代碼實際上工作,我只是尋找一個更好,也許更可讀的解決方案,雖然這是很容易理解我想要在這裏實現。

不管怎麼說,任何人有一個有關如何使用這個去的線索?

提前感謝!=)

回答

1

使用您switch語句組通過選擇器;那麼鍵將分別爲0到6。之後,您只需在每個組上使用Sum運算符即可。

在C#中,它應該是這樣的(你沒有範圍在C#case S):

var filtered = data 
    .Where(item => item.Age > 15 && item.Age <= 49) 
    .GroupBy(item => 
        { 
        if(item.Age > 15 && item.Age <= 19) 
         return 0; 
        else if(item.Age <= 24) 
         return 1; 
        else if(item.Age <= 29) 
         return 2; 
        else if(item.Age <= 34) 
         return 3; 
        else if(item.Age <= 39) 
         return 4; 
        else if(item.Age <= 44) 
         return 5; 
        else if(item.Age <= 49) 
         return 6; 
        }); 

之後,你可以創建一個字典:

var dict = filtered.ToDictionary(i => i.Key, i => /* do something with the sequence */); 
+0

+1這是你到達那裏的一個非常聰明和很好的答案! =)謝謝!另外,我的問題是如何在VB.NET中做到這一點?實際上,這是我的痛苦,儘管我會嘗試翻譯這個,即使它需要使用「New Action」或「New Func」的委託子。 – 2011-03-29 02:18:02

+0

是的,您必須針對vb中缺少的語言功能進行調整;它應該仍然是可行的,但不是很漂亮。儘管如此,我不能幫助你,因爲我不做vb,但是現在你應該有一個想法,要遵循什麼路線。 – Femaref 2011-03-29 02:19:22

+0

謝謝!我會嘗試你的解決方案,看看它是否適合我的需要,我懷疑它不會。感謝你的協助! =) – 2011-03-29 02:21:22