2010-10-10 145 views
1

我試圖生成表單的圖表:LINQ:用匿名類型處理

User A User B  Owes  Owed  Net 
Sam  David  $20  $10  $10 
Timbo  ODP  $30  $0  $30 

使用下面的查詢:

 var debt = from user in users 
        select new { 
        Username = username, 
        User = user, 
        Owes = owedBetween(username, user), 
        Owed = owedBetween(user, username), 
        Net = Owes - Owed // doesn't compile 
        }; 

的問題是,最後行不編譯。有沒有辦法在查詢中設置Net值,還是必須將其初始化爲零,然後再進行更改?

回答

15

嘗試使用let關鍵字:

var debt = from user in users 
       let owes = owedBetween(username, user) 
       let owed = owedBetween(user, username) 
       select new { 
       Username = username, 
       User = user, 
       Owes = owes, 
       Owed = owed, 
       Net = owes - owed 
       }; 
+0

+1優雅..... – CesarGon 2010-10-10 14:34:58

+1

+1:'let'正是我們所需要的。 – Ani 2010-10-10 14:35:28

1

嘗試:

Net = owedBetween(username, user) - owedBetween(user, username) 

順便說一句,我建議你用更好的名稱爲usernameuser。哪個是哪個?

+0

是啊,我知道了,我馬上就要重構。 – 2010-10-10 14:32:54

+0

偉大:-) ...... – CesarGon 2010-10-10 14:34:09