Linq Combine Fields

I just want to check if there is a more elegant way to accomplish this task with Linq. I greatly simplify the code for brevity. I will review my reasons in a minute, but this happens as follows:

(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 that it would be easy to make FullName = t.FirstName + "" + t.LastName, but imagine for a second that FirstName and LastName were big ugly built-in calculations, not just variables. So FullName = [big ugly calc 1] + [big ugly calc 2]. So, in the spirit of DRY, is there a better way to do this? My first thought is to write a function that gives me FirstName and LastName. But is there something better?

+3
source share
3 answers

, :

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 }

, , .

:

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 }
+8

, FullName .

:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return FirstName + " " + LastName; } }
}

linq:

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

You can do

public void SomeClassMethod()
{
    List<Person> people = new List<Person>();

    people.Add(new Person() { FirstName = "Bob", Surname = "Smith" });
    people.Add(new Person() { FirstName = "Sally", Surname = "Jones" });

    var results =
        from p in people
        let name = p.FirstName + " " + p.Surname
        select new
        {
            FirstName = p.FirstName,
            Surname = p.Surname,
            FullName = name
        };  
}

public class Person
{
    public String FirstName { get; set; }
    public String Surname { get; set; }
}
+2
source

Source: https://habr.com/ru/post/1723351/


All Articles