Lambda查询以前的参数访问

时间:2016-05-17 21:25:58

标签: c# lambda

是否可以访问先前条件的参数变量? 怎么做?

var result = collectionA
    .First(a => a.id == 1)
    .CollectionB
    .SelectMany(b => b.CollectionC)
    .Select(c => new { propA = a.id, propC = c.id });

2 个答案:

答案 0 :(得分:2)

你可以写

var result = collectionA
.Where(q => q.id == 1).Take(1) //it will be collection of 1 element
.Select(a => a
.CollectionB
.SelectMany(b => b.CollectionC)
.Select(c => new { propA = a.id, propC = c.id })).First();

(new [] { collectionA.First(q => q.id == 1) })
.Select(a => a
....

或只是

var a = collectionA.First(q => q.id = 1);
a.Select( .....

答案 1 :(得分:0)

解决方案基于@ Artem的答案:

var result = CollectionA
    .Where(a => a.id == 1)
    .SelectMany(b =>
        b.CollectionB
        .SelectMany(c => c.CollectionC)
        .Select(c => new { b.id, c.id })
    );