Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALiasing fields in linq

Tags:

c#

linq

This one seems like it should be pretty straightforward, but I couldn't quite figure it out or find anything on it. My query looks something like this:

from o in objects
          select new
          {
            o.ID,
            o.member.Number,
            o.member.Date,
            o.member.total,
            o.SequenceNumber,
            o.InputDate,
            o.Amount,
            o.Discount,
            Balance = o.Balance(),
            o.otherMember.CreatedBy,
          }

Notice there are quite a few times where i access o.member. In real life this is like 20 times (I'm aggregating a dataset for a grid). What I would like to do is be able to reference it like this :

select new
          {
            o.ID,
            m.Number,
            m.Date,
            m.total,
            o.SequenceNumber,
            o.InputDate,
            o.Amount,
            o.Discount,
            Balance = o.Balance(),
            o.otherMember.CreatedBy,
          }

But I'm not sure the right syntax to use. Is it possible to alias it at the top, or with a join somehow?

like image 242
captncraig Avatar asked Feb 22 '26 10:02

captncraig


1 Answers

You can do:

from o in objects
let m = o.member
select new { /* as per question */ };
like image 123
Jon Skeet Avatar answered Feb 24 '26 23:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!