如何在列表的一段中循环,而另一段保持不变

本文关键字:一段 循环 列表 | 更新日期: 2023-09-27 18:27:05

我正试图以的方式循环浏览列表

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

如何在列表的一段中循环,而另一段保持不变

沿着这些线的东西:

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

然后你可以进行

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

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

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