Linq Combine Fields

时间:2009-11-19 14:11:49

标签: c# linq

只是想查看是否有更优雅的方法来使用Linq完成此任务。为简洁起见,我大大简化了代码。我会在一分钟内介绍我的理由,但它是这样的:

(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!
}

是的,我知道执行FullName = t.FirstName +“”+ t.LastName会很简单,但让我们想象一下,FirstName和LastName是大丑的内联计算而不是简单的变量。所以FullName = [大难看的计算1] + [大难看的计算2]。因此,根据DRY的精神,有没有更好的方法可以做到这一点?我的第一个想法是编写一个给我FirstName和LastName的函数。但还有更好的东西吗?

3 个答案:

答案 0 :(得分:8)

嗯,你可以这样做:

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 }

答案 1 :(得分:2)

如果您没有使用匿名类型,则根本不能完全指定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 :(得分:2)

你可以做到

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