C#中利⽤Linq.Dynamic实现简单的动态表达式构建查询
背景介绍
在ADO.NET中我们可以根据⽤户输⼊的查询条件拼接出指定的SQL语句进⾏查询或者筛选出所需的数据,但是在ORM框架如EF
中,我们⼀般⽤LINQ操作数据查询,LINQ是否可以像SQL⼀样拼接查询条件呢?答案是可以的。这⼀技术叫Linq.Dynamic(动态
Linq),Linq.Dynamic的出现解决了本⼈⼼中的疑惑,不然总感觉少了什么。不管怎么样,我们⾸先要做的是去⽹上各种⼤神的资料,本
⽂参考如下⼏篇资料:
另外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 a 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();
}
执⾏效果如下图所⽰:
希望对⼤家有所帮助!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论