在 Dynamic Linq 中使用 Any() 和 Count()

发布于 2024-11-17 14:55:11 字数 446 浏览 3 评论 0原文

我正在尝试编写动态 Linq 库查询来根据条件获取记录, 订单数大于 3 且 ShipVia 字段等于 2 的客户。

以下是我尝试过的语法。

object[] objArr = new object[10];
objArr[0] = 1;
IQueryable<Customer> test = db.Customers.Where("Orders.Count(ShipVia=2)", objArr);

IQueryable<Customer> test = db.Customers.Where("Orders.Any(ShipVia=2).Count()", objArr);

两者都不起作用。在第二个查询中 Any 返回 true,因此它不适用于 Count。 建议我一种实现此方法的方法。

I am trying to write dynamic Linq Library query to fetch record on condition,
Customers who has order count is greater than 3 and ShipVia field equal 2.

Below is my syntax what i have tried.

object[] objArr = new object[10];
objArr[0] = 1;
IQueryable<Customer> test = db.Customers.Where("Orders.Count(ShipVia=2)", objArr);

and

IQueryable<Customer> test = db.Customers.Where("Orders.Any(ShipVia=2).Count()", objArr);

But both are not working. In second query Any returns true so it won't work with Count.
Suggest me a way to implement this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

与风相奔跑 2024-11-24 14:55:11

如果您必须使用 Dynamic Linq,您的查询应该如下所示:

db.Customers.Where("Orders.Count(ShipVia == 2) > 3");

If you HAVE to use Dynamic Linq, your query should look like that:

db.Customers.Where("Orders.Count(ShipVia == 2) > 3");
浅浅 2024-11-24 14:55:11

像这样的事情怎么样?

IQueryable<Customer> test = db.Customers.Where(c => c.Orders.Where(o => o.ShipVia ==2).Count() >2);

How about something like this.

IQueryable<Customer> test = db.Customers.Where(c => c.Orders.Where(o => o.ShipVia ==2).Count() >2);
牵强ㄟ 2024-11-24 14:55:11
var grp = db.Customers.Where("ShipVia=2").GroupBy("ShipVia");

var test = from a in grp
             where a.Count() > 3
             select a.Key;  
var grp = db.Customers.Where("ShipVia=2").GroupBy("ShipVia");

var test = from a in grp
             where a.Count() > 3
             select a.Key;  
江湖正好 2024-11-24 14:55:11
IQueryable<Customer> test = 
    from c in db.Customers
    from o in c.Orders
    where o.ShipVia == 2 // NOTE you need == not = for compare
    group c by c into grp
    select new {customer = grp.key, ordercount = grp.Count() };

未经测试,但我相信这应该在一个声明中完成所有操作,假设订单是客户内的集合。

请注意,where 子句中的单个 = 非常危险,因为它会将 2 分配给所有 Shipvias 而不是 test (==)

IQueryable<Customer> test = 
    from c in db.Customers
    from o in c.Orders
    where o.ShipVia == 2 // NOTE you need == not = for compare
    group c by c into grp
    select new {customer = grp.key, ordercount = grp.Count() };

Untested but I believe this should do it all in one statement, assuming Orders are a collection within Customer.

Note that your single = in your where clause is very dangerous as it'll assign 2 to all shipvias instead of test (==)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文