开发者

LINQ: Dealing with anonymous types

I'm trying to generate a chart of the form:

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

Using the following query:

        var debt = from user in users
               开发者_如何学Python    select new {
                     Username = username, 
                     User = user,
                     Owes = owedBetween(username, user),
                     Owed = owedBetween(user, username),
                     Net = Owes - Owed // doesn't compile
                   };

The problem is that that last line doesn't compile. Is there a way to set up the Net value in the query, or must I initialize it to zero then change it afterwards?


Try using the let keyword:

  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
               };


Try:

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

By the way, I suggest you use better names for username and user. Which is which?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜