LINQ to SQL C # COALESCE

Given the following table:

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

I want to create one 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 can’t figure out how to do this in LINQ.

The closest I got:

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) + ", ")
           }

Creates one column and two rows:

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

Transformations are not important to the problem. Columns are defined as float, although all are integers. The key is the COALESCE function, I cannot figure out how to do this in LINQ.

+3
source share
4 answers

, LINQ to SQL T-SQL. COALESCE ( , #?) - , SQL Server @SIZES. AFAIK LINQ to SQL .

, , SQL. , , .

var query = 
    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) + ", ")
           };

var result = string.Join(string.Empty, query.Select(r => r.SIZES).ToArray());
+1

?? ( null coalesce), :

t.Length ?? 0
+8

int SQL :

var query = 
    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 g.Key;

var sizeStrings = from s in query.AsEnumerable()
                  select string.Format("{0} x {1}", s.Length, s.Width);

var result = string.Join(", ", sizeStrings.ToArray());
0

.Aggregate, :

(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) + ", ")
       }).Aggregate((x,y) => x + y)

, . , SQL, .

0

Source: https://habr.com/ru/post/1714630/


All Articles