Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Combine Fields

Tags:

c#

linq

Just wanted to check to see if there's a more elegant way to accomplish this task using Linq. I'm greatly simplifying the code for brevity. I'll go into my reasons in a minute, but it goes like this:

(from t in doc.Descendants(p + "Task")
where t.Element(p + "Name") != null
select new {
     FirstName = t.FirstName,
     LastName = t.LastName,
     FullName = FirstName + " " + LastName  // Error!
}

Yes, I know it would be simple to do FullName = t.FirstName + " " + t.LastName, but let's imagine for a second that FirstName and LastName were big ugly inline calculations and not simple variables. So FullName = [big ugly calc 1] + [big ugly calc 2]. So in the spirit of DRY, is there a better way this could be done? My first thought is to write a function that gives me FirstName and LastName. But is there something better?

like image 546
billb Avatar asked Feb 11 '26 16:02

billb


1 Answers

Well, you can do:

from t in doc.Descendants(p + "Task")
where t.Element(p + "Name") != null
let FirstName = t.FirstName
let LastName = t.LastName
select new { FirstName, LastName, Fullname = FirstName + LastName }

It will be slightly inefficient in terms of the projections it's going through, but it'll work.

Slightly more efficient would be:

from t in doc.Descendants(p + "Task")
where t.Element(p + "Name") != null
select new { t.FirstName, t.LastName } into x
select new { x.FirstName, x.LastName, FullName = x.FirstName + x.LastName }
like image 61
Jon Skeet Avatar answered Feb 14 '26 05: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!