LINQ to SQL C# COALESCE

Najitaka picture Najitaka · Aug 7, 2009 · Viewed 14.3k times · Source

Given the following table:

Length | Width | Color | ID
===========================
    18 |    18 |  blue |  1
---------------------------
    12 |    12 |   red |  1
---------------------------

I want to produce a single column/row:

 SIZES
 =================
 18 x 18, 12 x 12,

I can do this in SQL as follows:

DECLARE @SIZES VARCHAR(8000)
SELECT @SIZES = COALESCE(@SIZES, '') + Convert(varchar(80), [Length]) + ' x ' + 
                Convert(varchar(80), [Width]) + ', '
FROM table
where ID = 1
GROUP BY [Length], [Width]
ORDER BY [Length], [Width]
SELECT SIZES = @SIZES

But I cannot figure out how to do this in LINQ.

The closest I got was:

from t in table
where id == 1
group t by new {
                 t.Length,
                 t.Width
               } into g
orderby g.Key.Length, g.Key.Width
select new {
             SIZES = (Convert.ToInt32(g.Key.Length) + " x " +
                      Convert.ToInt32(g.Key.Width) + ", ")
           }

Which produces one column and two rows:

SIZES
========
18 x 18,
12 X 12,

The converts are unimportant to the problem. The columns are defined as floats though all are integers. The key is the COALESCE function I cannot figure out how to do that in LINQ.

Answer

mmx picture mmx · Aug 7, 2009

Try ?? (null coalesce operator) like:

t.Length ?? 0