Ronjon
Ronjon

Reputation: 1849

return one string with multiple column value linq

I have a query.

Is it possible to return One string with multiple column value in linq ??

Like this

string ProductName = ((from P in DataModel.DIS_PRODUCT
                       join M in DataModel.SET_PACK_UNIT on P.PUNIT_ID equals M.ID
                       where P.PRODUCT_ID == ProdictId
                       select P.PRODUCT_NAME +" " + P.WEIGHT + " "+ M.UNIT_SYMBLE)
                       .Take(1)
                     ).ToString();

Upvotes: 1

Views: 3009

Answers (2)

Otto Kanellis
Otto Kanellis

Reputation: 3708

Another more clear way is the following

var ProductsQueryItem = (from p in Products
              select new
              {
                  Name = e.ProductName+ " " + e.weight +e.UNIT_SYMBLE
              })
.FirstOrDefault();

Now you can use it directly with ProductsQueryItem .Name

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500105

You're 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.DIS_PRODUCT
                      join M in DataModel.SET_PACK_UNIT
                        on P.PUNIT_ID equals M.ID
                      where P.PRODUCT_ID == ProdictId
                      select P.PRODUCT_NAME + " " + P.WEIGHT + " "+ M.UNIT_SYMBLE)
                     .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.DIS_PRODUCT
            join M in DataModel.SET_PACK_UNIT
              on P.PUNIT_ID equals M.ID
            where P.PRODUCT_ID == ProdictId
            select new { P.PRODUCT_NAME, P.WEIGHT, M.UNIT_SYMBLE };

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

Upvotes: 2

Related Questions