linq

---恢复内容开始---

LINQ中let、group、into子句的用法

let用法

let子句用来保存表达式的结果,如 :范围变量的方法运算结果。下列查询会返回所有员工薪水的置。eg:

  var salaryQuery =

                from company in companies

                from emp in company.Employees

                let salary = 总和

                select salary;

group用法

创建依程序指定的索引键组织的群组序列对象,为IG欧平泛型集合,索引键可以是任何的数据类型。eg:

 var groups = from word in words

                         orderby word ascending

                         group word by word.Length into lengthGroups

                         orderby lengthGroups.Key descending

                         select new { Length = lengthGroups.Key, Words = lengthGroups };

into用法:

LINQ子句可以用于创建暂时识别项,将groupjoinselect子句的结果保存至新的识别项。此识别项本身可以是额外查询命令的产生器。在groupselect子句中使用时,会视为“接续(Continuation)”查询动作,一般只有需要在群组上执行额外查询作业时,才会在group子句中使用intoeg

 var groups = from word in words

                         orderby word ascending

                         group word by word.Length into lengthGroups

                         orderby lengthGroups.Key descending

                         select new { Length = lengthGroups.Key, Words = lengthGroups,price=lengthGroups.sum(n=>n.price)};

在linq 使用 join 后会提示:LINQ to Entities 不识别方法“System.String ToString()”,因此该方法无法转换为存储表达式。

解决方法有两种

 一、使用SqlFunctions

date=SqlFunctions.DateName("yyyy", o.CreatedOn)
                            + "-" +
                            SqlFunctions.StringConvert((decimal)SqlFunctions.DatePart("mm", o.CreatedOn)).Trim()
                            + "-" +
                            SqlFunctions.DateName("dd", o.CreatedOn)
结果:

二、Linq-to-entities 转换到Linq-to-objects  使用:AsEnumerable() :效率会比较低

date=c.CreatedOn.ToString("yyyy-MM-dd"),//如果数据库里的日期字段可以为null,则CreatedOn.ToString("yyyy-MM-dd")这种方式是不可以的,如果不为null则可以;结果和上面一样

三、Empty 和 Enumerable  用法

Empty<T>和DefaultIfEmpty(IEnumerable<T>)都是Enumerable类的静态方法,给出了当返回的集合类型为空时的处理方法:

● 如果想获取一个空的集合,使用Enumerable.Empty<T>()
● 如果想给获取到的、空的集合一个默认值,使用Enumerable.DefaultIfEmpty(IEnumerable<T>)

原文地址:https://www.cnblogs.com/lp73/p/8398077.html