如何循环一段列表而另一段保持不变

时间:2015-12-17 08:05:48

标签: c# .net list loops foreach

我试图按顺序遍历列表

var grp = profile.where(pro => pro.Age == AgeRange.group13_17).ToArray

工作正常但我也希望能够循环通过另一个值范围,而上述查询保持不变,即

pro.Age = AgeRange.group13_17 

我希望能够遍历属于同一年龄组的每个收入等级范围。下面是我在C#

中列表的结构
var IncomeAge = new List<RealIncomeAge>();
{
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class1 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class2 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class3 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class4 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class5 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class6 });
    IncomeAge.Add(new RealIncomeAge { RealAge = AgeRange.group18_24, RealIncome = IncomeRange.class7 });
}

2 个答案:

答案 0 :(得分:2)

沿着这些方向:

var groups = IncomeAge.GroupBy(ia => ia.RealAge)

然后你可以做一个

foreach (var item in groups.Where(g => g.Key.Age == AgeRange.group13_17))
  Console.WriteLine(item)

答案 1 :(得分:1)

您可以先按年龄段进行分组,然后按如下方式选择组中的所有元素:

//group by
var groups = IncomeAge.GroupBy(ia => ia.RealAge);

//select where age group is group18_24
foreach (var item in groups.SelectMany(ra => ra.Where(a=>a.RealAge==AgeRange.group18_24))) 
    Console.WriteLine(item.RealIncome);