使用Linq到对象以到达层次结构深处的对象 [英] Using Linq to objects to get to an object deep in the hierarchy

查看:92
本文介绍了使用Linq到对象以到达层次结构深处的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Linq非常陌生,而我正在为此而苦苦挣扎.基本上,我有一个工人"集合,每个对象本身都包含一个"WorkerOperatorAssignments"集合,每个对象都包含一个"Operator"对象.

Quite new to Linq, and I'm struggling with this one. Basically I have a collection of "Workers", which each object itself contains a collection of "WorkerOperatorAssignments", which each object contains an "Operator" object.

工人(集合)-> WorkerOperatorAssignments(集合)-> 运算符(对象)

Workers (collection) -> WorkerOperatorAssignments (collection) -> Operator (object)

在某些情况下,我希望使用Linq返回操作员记录.到目前为止,我有以下内容:

I wish to return the Operator record in certain circumstances using Linq. I have the following so far:

Operator TillLogin = WorkersCollection.Where(w => 
    w.WorkerOperatorAssignments.Any(a => 
        a.Operator.TypeCode == OperatorTypeCode.TillOperator)
);

但是显然,这将返回一组工作器,其中包含根据where子句的Operator记录.在这种情况下,如何只返回实际的操作员记录?

But this obviously returns a collection of workers which contain an Operator record as per the where clause. How do I return just that actual Operator record in this condition?

更新:

谢谢大家的回答,帮了我很多忙.我已将完整查询修改为:

Thank you all for the answers, helped me a bunch. I have amended my full query to:

Operator TillLogin = Response.Payload.Party.Workers
      .SelectMany(w => w.WorkerOperatorAssignments)
      .Select(a => a.Operator)
      .Where(o => o.TypeCode.Trim() == OperatorTypeCode.TillOperator)
      .SingleOrDefault();

推荐答案

您可以使用SelectMany ...来获取WorkerOperatorAssignments,然后使用Select来获得Operator.然后,您可以筛选操作符.

You can get at the WorkerOperatorAssignments using a SelectMany...and then at the Operator using Select. Then you can just filter on the operators.:

 IEnumerable<Operator> tillOperators = 

 // flatten the WorkerOperatorAssignments
 WorkersCollection.SelectMany(w => w.WorkerOperatorAssignments)
   // get the Operator off each WorkerOperatorAssignment
   .Select(a => a.Operator)
   // filter the Operators
   .Where(o => o.TypeCode == OperatorTypeCode.TillOperator));

这篇关于使用Linq到对象以到达层次结构深处的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆