LINQ:处理匿名类型

时间:2010-10-10 14:29:02

标签: c# 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值,还是必须将其初始化为零然后再更改它?

2 个答案:

答案 0 :(得分: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
               };

答案 1 :(得分:1)

尝试:

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

顺便说一句,我建议您为usernameuser使用更好的名称。哪个是哪个?