Lakhae
Lakhae

Reputation: 1899

How to concatenate two fields in LINQ?

I am trying to combine two fields for e.g. FullName = FirstName + LastName

How can I accomplish in the following code?

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

Upvotes: 1

Views: 679

Answers (1)

Habib
Habib

Reputation: 223257

Looks like CreatedBy in Item is a type of string property and since in your query you are using select new it is creating an anonymous type. You can modify it like:

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

So your complete query would be like:

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(), 
};

Upvotes: 4

Related Questions