使用Linq对象来到达层次结构深处的对象

时间:2011-12-14 15:59:08

标签: linq

Linq很新,我正在努力解决这个问题。基本上我有一个“Workers”集合,每个对象本身都包含一个“WorkerOperatorAssignments”集合,每个对象包含一个“Operator”对象。

  

工人(收藏) - > WorkerOperatorAssignments(collection) - >   运营商(对象)

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

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

但是这显然会返回一个工人集合,其中包含一个根据where子句的操作员记录。如何在这种情况下返回实际的操作员记录?

更新:

谢谢大家的答案,帮了我一堆。我已将完整查询修改为:

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

4 个答案:

答案 0 :(得分:2)

您可以使用SelectMany获取WorkerOperatorAssignments ...然后使用Select选择Operator。然后你可以过滤运算符。:

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

答案 1 :(得分:2)

var operators = 
    from worker in WorkersCollection
    from workerAssignment in worker.WorkerOperatorAssignments
    where workerAssignment.Operator.TypeCode == OperatorTypeCode.TillOperator
    select workerAssignment.Operator;

答案 2 :(得分:2)

这听起来像你想要的:

var tills = from worker in WorkersCollection
            from assignment in worker.WorkerOperatorAssignments
            where assignment.Operator.TypeCode == OperatorTypeCode.TillOperator
            select assignment.Operator;

var firstTillLogin = tills.First(); // Or whatever...

注意最后一部分,从所有匹配运算符序列到第一部分。您可能想要第一个,FirstOrDefaultLastLastOrDefaultSingleSingleOrDefault - 或者您可能只想处理所有这些问题。我们无法说出来。

答案 3 :(得分:1)

Operator TillLogin = WorkersCollection
    .SelectMany(w => w.WorkerOperatorAssignments) //get all the worker assignments
    .Select(oa => oa.Operator) //from each select the operator
    .Single(o => o.TypeCode == OperatorTypeCode.TillOperator); //find the single operator that matches the code

如果没有一个具有该类型代码的运算符,则会抛出异常。如果您不想抛出异常,而是TillLoginnull,请使用SingleOrDefault(假设运算符不是值类型,否则它将是默认值)