![](/img/trans.png)
[英]What is the equivalent Linq Where code to IF condition in Vb.Net?
[英]What would be the Linq code for this grouping using VB.NET 2008?
我的年齡在0至119歲之間。
我希望根據以下假設對15歲至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;
});
除了我嘗試與New Action(Of T1, T2)
或Func(Of Double?, TKey)
一起使用外,我似乎無法在VB.NET 2008中實現這一點。 我對這些都不滿意! =(( 潛在問題:為什么在VB.NET中使用lambdas這么復雜!?
我的代碼實際上有效,我只是在尋找一個更好的,也許是更具可讀性的解決方案,盡管這很容易理解我在這里想要實現的目標。
無論如何,有人對如何使用此方法有任何線索嗎?
提前致謝! =)
在選擇器分組中使用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 */);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.