Nick Heiner
Nick Heiner

Reputation: 122392

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
                   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?

Upvotes: 1

Views: 119

Answers (2)

Dave Markle
Dave Markle

Reputation: 97671

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

Upvotes: 15

CesarGon
CesarGon

Reputation: 15325

Try:

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

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

Upvotes: 1

Related Questions