如何在LINQ中连接两个字段?

时间:2014-02-12 17:06:13

标签: linq

我正在尝试将两个字段合并为例如FullName = FirstName + LastName

如何在以下代码中完成?

IEnumerable<Item> Items = from item in _entities.Items
where Item.ID == Id 
orderby contractItem.Item.ItemName
select new Item
{
   Id = item.ID,
   ...
   CreatedBy = (from employee in _entities.Employees
                where employee.UserID == item.CreatedBy
                select new {
                             FirstLast = employee.FName + " " + employee.LName}).FirstOrDefault(), // <---- gives me an error
   ...
};

1 个答案:

答案 0 :(得分:4)

CreatedBy中的Item似乎是string属性的一种类型,因为在您的查询中,您使用的是select new,它正在创建一个匿名类型。你可以修改它:

    (from employee in _entities.Employees
    where employee.UserID == contractItem.CreatedBy
    select employee.FName + " " + employee.LName).FirstOrDefault()

所以你的完整查询就像:

IEnumerable<Item> Items = from item in _entities.Items
where Item.ID == Id 
orderby contractItem.Item.ItemName
select new Item
{
   Id = item.ID,
   ...
   CreatedBy = (from employee in _entities.Employees
                where employee.UserID == item.CreatedBy
                select employee.FName + " " + employee.LName).FirstOrDefault(), 
};