【问题标题】:Using LINQ to loop through inner class properties in outer class collection and group by outer class properties使用 LINQ 循环遍历外部类集合中的内部类属性并按外部类属性分组
【发布时间】:2014-09-27 14:21:35
【问题描述】:

利用 Q&A 处理循环遍历对象的属性(Loop Through An Objects Properties In C#Using LINQ to loop through inner class properties in outer class collection),您可以:

  • Class1 对象的集合(即 listObj1)
  • 每个 Class1 包含属性和 Class2 对象的集合(即 dictObj2)

你会怎么做:

  • 高效确定内部类(Class2)的属性
  • 循环遍历内部类 (Class2) 的属性
  • 循环遍历 Class1 对象 (listObj1) 的集合,选择 Class2 属性的所有实例
  • 输出 Class2 属性的集合(例如,第一次迭代将返回 MeasurementA 的集合,每个 Class1 对象都有一个)。
  • 按 Class1.PropertyA 和 Class1.PropertyB 对集合进行分组

请在下面找到所涉及类的粗略地图。

我一直在尝试使用 LINQ 查询但没有成功。由 Konrad Kokosa 提供的answer 就是其中的大部分。任何想法或指导将不胜感激。

class MainClass {
  List<Class1> listObj1
}

class Class1 {
  // a number of fields including...
  int PropertyA { get; set; }
  int PropertyB { get; set; }
  Dictionary<int, Class2> dictObj2 { get; set; }
}

class Class2 {
  // a number of fields all of type double...
  double MeasurementA { get; set; }
  double MeasurementB { get; set; }
  double MeasurementC { get; set; }
}

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:

    只是循环:

    foreach(var cls1 in listObj1)
    {
        int tempA = cls1.PropertyA;
        foreach(var cls2 in cls1.dictObj2)
        {
             double tempB = cls2.MeasurementB;
        }
    }
    

    过滤/高效循环:

    foreach(var cls1 in listObj1.Where(c1=> c1.PropertyA > 5 && c1.PropertyB > 3))
    {
        int tempA = cls1.PropertyA;
        foreach(var cls2 in cls1.dictObj2.Where(c2=> c2.MeasurementA >= 10))
        {
             double tempB = cls2.MeasurementB;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多