如果你想要这个“在一个查询中”,大多数是“文字形式”,你必须做类似的事情:
from t in
(
(
from a in source
where somecondition(a)
join b in source2
on a.key equals b.key
where someothercondition(a, b)
select new { a = a, b = b }
).Select((x, i) => new { index = i, a = x.a, b = x.b } )
)
select new {
f1 = t.a.f1,
oldf2 = func(t.a.field, t.b.field),
newf2 = func(t.a.field, t.b.field, t.index)
// ... (20 somthing more projected fields) }
但这太可怕了。
我宁愿把它全部放在.
形式上:
a
.Where(a => somecondition(a))
.Join(b, a => a.key, b => b.key, (a,b) => new { a = a, b = b })
.Where(pair => somecondition(pair.a, pair.b))
.Select((t, i) => new
{
f1 = t.a.f1,
oldf2 = func(t.a.field, t.b.field),
newf2 = func(t.a.field, t.b.field, i)
// ...
});
连接语法更难看,但至少你没有混淆语法。
你甚至可能更喜欢做
var pairs =
from a in source
where somecondition(a)
join b in source2
on a.key equals b.key
where someothercondition(a, b)
select new { a = a, b = b };
var indexedPairs = pairs.Select((x, i) => new { index = i, a = x.a, b = x.b } );
var projectedIndexedPairs =
from t in indexedPairs
select new {
f1 = t.a.f1,
oldf2 = func(t.a.field, t.b.field),
newf2 = func(t.a.field, t.b.field, t.index)
// ... (20 somthing more projected fields)
};
但这不是“一次查询”...
(这是很多 LINQ,其中可能存在一些语法错误,但您大致了解。)
令人眼花缭乱的灵感闪现
你提到let
魔法让我想到了这一点。它似乎在我写的一个快速示例中起作用。
// Copious commenting to explain what you're doing.
int x = 0;
// Copious commenting to explain what you're doing.
var query =
from a in source
where somecondition(a)
join b in source2
on a.key equals b.key
where someothercondition(a, b)
let i = x++
select new {
f1 = a.f1,
oldf2 = func(a.field, b.field),
newf2 = func(a.field, b.field, i),
// ... (20 somthing more projected fields)
};
更新:这是相当脆弱的。例如,如果您迭代query
两次,则索引会不断增加。(即它不会重置为零。)