如果你想這個「在一個查詢」,與廣大的「文字表」,你必須做一些事情,如:
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的,有可能是在那裏一些語法錯誤,但你得到的總體思路。)
盲目化靈感FLASH
你的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
兩次,索引不斷遞增。 (即不重置爲零)。
你的問題不清楚。請添加一些示例代碼。 – jeroenh
這是LINQ to SQL嗎? –
不,它的正常linq – mmix