LINQ to SQL C# COALESCE

落爺英雄遲暮 提交于 2019-12-01 22:25:20

I don't think LINQ to SQL supports this T-SQL trick. The COALESCE isn't really the issue (as Mehrdad points out the equivalent in C# is ??) -- it's the fact that SQL Server aggregates each result via string concatenation into the variable @SIZES. AFAIK LINQ to SQL can't construct this type of query.

This will yield your desired result, but the string concatenation is performed on your side, not on the SQL server side. That probably doesn't matter.

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

Try ?? (null coalesce operator) like:

t.Length ?? 0

I would just return the int sizes from SQL and do the string building client-side:

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

You could use the .Aggregate function, like so:

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

This should kick out a single string, like you want. Aggregate just internally maintains the exact same variable you had defined in the SQL, just implicitly.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!