【问题标题】:LINQ to return list of Object filtered on a property of a Child object in nested List<>LINQ 返回根据嵌套 List<> 中子对象的属性过滤的对象列表
【发布时间】:2015-02-23 23:02:08
【问题描述】:

我正在寻找有关 LINQ 查询的帮助,以过滤嵌套列表中自定义对象的属性/枚举,并希望在返回列表中维护父对象。

例如/清晰度/示例代码,我有一个父对象,其中有一个基于类和枚举的列表:

public class Stage {
  public String Name { get; set;}
  public List<Evaluation> MyEvaluations { get; set;}
}
public class Evaluation {
  public float Result { get; set; }
  public enumResultType ResultType { get; set; }
}
public enum enumResultType { 
A,B,C 
}

Once 可以通过以下方式模拟示例数据:

List<Stage> ParentList = new List<Stage>();
Stage Stage1 = new Stage() { Name = "Stage1", 
MyEvaluations = new List<Evaluation>() { 
new Evaluation() { ResultType = enumResultType.A, Result=5 },
new Evaluation() { ResultType = enumResultType.B, Result=10},
new Evaluation() { ResultType = enumResultType.B, Result=11}, 
new Evaluation() { ResultType = enumResultType.C, Result=5}
}};
Stage Stage2 = new Stage() { Name = "Stage2",
MyEvaluations = new List<Evaluation>() { 
new Evaluation() { ResultType = enumResultType.A, Result=10},
new Evaluation() { ResultType = enumResultType.B, Result=20},
new Evaluation() { ResultType = enumResultType.C, Result=20}}};
ParentList.Add(Stage1);
ParentList.Add(Stage2);

我希望能够通过 LINQ 做的是从 Parentlist 对象中选择所有只有一个过滤列表的项目,其中评估列表中的 ResultType 匹配一个适当的健康)状况... 我不想多次重复父对象(见selectmany),而是过滤掉MyEvaluations的列表,其中ResultType匹配,如果这个列表有项目(它会)用父母。

我玩过:

ParentList.Select(x => x.MyEvaluations.FindAll(y => y.ResultType==enumResultType.B)).ToList();

但是这只会返回内部列表...而

ParentList.Where(x => x.MyEvaluations.Any(y => y.ResultType==enumResultType.B)).ToList();

返回 ANY.. 但是我错过了如何过滤 MyEvaluations 的列表..

在我的示例/示例数据中,我想查询 ParentList 中 ResultType = enumResultType.B; 的所有情况

所以希望得到一个相同类型的列表,但没有等于ResultType.A.C 的“评估”

根据虚拟数据,我希望得到的东西会:

returnList.Count() - 2 个项目 (Stage1 / Stage2) 并在该 Stage1 内 --> foreach (item.Result : 10, 11 Stage2 --> foreach (item.Result : 20

这是否可以在不使用新匿名类型的投影的情况下完成,因为我希望列表保持整洁,以便稍后在 DataBinding 中使用,并且我会迭代许多 ResultTypes?

感觉我错过了一些相当简单但对 LINQ 和 lambda 表达式来说相当新的东西。

【问题讨论】:

    标签: linq list c#-4.0 lambda nested


    【解决方案1】:

    您是否已经尝试过这些方法?或者这不是您想要的?

    //creating a new list 
    var answer = (from p in ParentList
                 select new Stage(){
                 Name = p.Name,
                 MyEvaluations = p.MyEvaluations.Where(e => e.ResultType == enumResultType.B).ToList()
                 }).ToList();
    
    //in place replacement               
    ParentList.ForEach(p => p.MyEvaluations = p.MyEvaluations.Where(e => e.ResultType == enumResultType.B).ToList());
    

    【讨论】:

    • 谢谢!是的,这是有道理的!我一直拒绝创建一个新对象,因为认为可能有一种更有效的方法可以通过某种过滤器过滤原始列表,但这很有效。内联替换会修改列表,因此不能在我的情况下使用,因为我必须根据不同的 EnumResultTypes 对 ParentList 进行数据绑定,但创建新列表适用于我的用例场景。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2013-07-05
    • 1970-01-01
    • 2020-03-11
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多