Sunday, December 2, 2018

Concatenate two column values in LinQ Lambda Expression

Using Take(1) which means you're still getting an IEnumerable<string> or an IQueryable<string>. Just use First() (or possibly FirstOrDefault()) instead of Take(1) and you can drop the ToString() call as well.

string productName = (from P in DataModel.Product
                      join M in DataModel.ProductPackUnit
                        on P.PUNIT_ID equals M.ID
                      where P.PRODUCT_ID == ProdictId
                      select P.PRODUCT_NAME + " " + P.WEIGHT + " "+ M.UNIT)
                     .FirstOrDefault();

That will only work if your LINQ provider supports the string concatenation operation. An alternative is to fetch just the columns you want, and then concatenate at the caller:

var query = from P in DataModel.Product
            join M in DataModel.ProductPackUnit
              on P.PUNIT_ID equals M.ID
            where P.PRODUCT_ID == ProdictId
            select new { P.PRODUCT_NAME, P.WEIGHT, M.UNIT };

var result = query.FirstOrDefault();
if (result != null)
{
    string productName = result.PRODUCT_NAME + " " +
                         result.WEIGHT + " " +
                         result.UNIT;
    // Use the name
}
else
{
    // No results
}

No comments:

Post a Comment