背景介绍
在ADO.NET中我们可以根据用户输入的查询条件拼接出指定的SQL语句进行查询或者筛选出所需的数据,但是在ORM框架如EF中,我们一般用LINQ操作数据查询,LINQ是否可以像SQL一样拼接查询条件呢?答案是可以的。这一技术叫Linq.Dynamic(动态Linq),Linq.Dynamic的出现解决了本人心中的疑惑,不然总感觉少了什么。不管怎么样,我们首先要做的是去网上找各种大神的资料,本文参考如下几篇资料:
Linq.Dynamic基本介绍1:https://www.cnblogs.com/myzony/p/9143692.html
Linq.Dynamic基本介绍2:https://blog.csdn.net/flyingdream123/article/details/79962525
另外Linq.Dynamic是由外国大神所创,源码在其个人主页上也有:源码地址
首先,需要在NuGet程序包中引入Linq.Dynamic.Core并引用其命名空间才能使用。
其次,使用动态查询必须先调用AsQueryable()方法。
static void Main(string[] args){List<Phone> PhoneLists = new List<Phone>(){new Phone { Country = "中国", City = "北京", Name = "小米" },new Phone { Country = "中国",City = "北京",Name = "华为"},new Phone { Country = "中国",City = "北京",Name = "联想"},new Phone { Country = "中国",City = "台北",Name = "魅族"},new Phone { Country = "日本",City = "东京",Name = "索尼"},new Phone { Country = "日本",City = "大阪",Name = "夏普"},new Phone { Country = "日本",City = "东京",Name = "松下"},new Phone { Country = "美国",City = "加州",Name = "苹果"},new Phone { Country = "美国",City = "华盛顿",Name = "三星"},new Phone { Country = "美国",City = "华盛顿",Name = "HTC"}};var Lists = PhoneLists.AsQueryable().Where("Country = @0 And City = @1", "中国", "北京").OrderBy("Name,City").Select("new (Country as Country,City as City,Name as Name)");var dLists = Lists.ToDynamicList();foreach (var list in dLists){Console.WriteLine(list.Country + "-" + list.City + "-" + list.Name);}Console.Read();}
运行效果如下图所示:
当然也支持GroupBy()查询,代码如下:
static void Main(string[] args){List<Phone> PhoneLists = new List<Phone>(){new Phone { Country = "中国", City = "北京", Name = "小米" },new Phone { Country = "中国",City = "北京",Name = "华为"},new Phone { Country = "中国",City = "北京",Name = "联想"},new Phone { Country = "中国",City = "台北",Name = "魅族"},new Phone { Country = "日本",City = "东京",Name = "索尼"},new Phone { Country = "日本",City = "大阪",Name = "夏普"},new Phone { Country = "日本",City = "东京",Name = "松下"},new Phone { Country = "美国",City = "加州",Name = "苹果"},new Phone { Country = "美国",City = "华盛顿",Name = "三星"},new Phone { Country = "美国",City = "华盛顿",Name = "HTC"}};var Lists = PhoneLists.AsQueryable().GroupBy("new (Country as Country,City as City)");var dLists = Lists.ToDynamicList();foreach (var list in dLists){Console.WriteLine(list + ":");foreach (var lis in list){Console.WriteLine(lis.Country + "-" + lis.City + "-" + lis.Name);Console.WriteLine($"{lis.Country} - {lis.City} - {lis.Name}");}}Console.Read();}
执行效果如下图所示:
希望对大家有所帮助!