LINQ to SQL C#COALESCE

时间:2009-08-07 15:46:12

标签: sql linq coalesce

鉴于下表:

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

我想生成一个列/行:

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

我可以在SQL中执行以下操作:

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

但我无法弄清楚如何在LINQ中执行此操作。

我最接近的是:

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

生成一列和两行:

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

皈依者对这个问题并不重要。虽然列都是整数,但列被定义为浮点数。关键是COALESCE函数我无法弄清楚如何在LINQ中做到这一点。

4 个答案:

答案 0 :(得分:9)

尝试??null coalesce operator),例如:

t.Length ?? 0

答案 1 :(得分:1)

我不认为LINQ to SQL支持这种T-SQL技巧。 COALESCE并不是真正的问题(因为Mehrdad指出C#中的等价物是??) - 事实上,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());

答案 2 :(得分:0)

我只会从SQL返回int大小并执行构建客户端的字符串:

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

答案 3 :(得分: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)

这应该像你想要的那样踢出一个字符串。 Aggregate只是在内部维护你在SQL中定义的完全相同的变量,只是隐式地。