【问题标题】:Multiple conditional where on list c#列表中的多个条件位置 c#
【发布时间】:2021-01-14 00:56:07
【问题描述】:

我需要在列表中添加多个条件,但我不能

List<Account> accounts = getAccount();

在我的列表之后,我需要应用多个这样的条件,我该怎么做,因为我不能在 prdicate 上创建And。这是我的代码

Func<Account, bool> predicate = X => true;

                if (request.id!= 0)
                {
                    predicate = predicate.And(giftCard => giftCard.Id == request.Id);
                }
                if (request.code> 0)
                {
                    predicate = predicate.And(giftCard => giftCard.code== request.code);
                    }
                if (request.cjn> 0)
                {
                    predicate = predicate.And(giftCard => giftCard.cjn== request.cjn);
                    }
var resuly=accounts.where(predicate);

【问题讨论】:

  • var query = myList.Where(); if(x){ query=query.Where();}List 是一个容器,它没有条件或过滤器。查询由 LINQ 提供
  • 只需在Where 中添加条件,如下所示:list.Where(item =&gt; item.Id == request.Id &amp;&amp; item.Code == request.Code &amp;&amp; ...)
  • 但我需要让它们有条件地说明为什么我可以将它们放在 where 中
  • @DhouhaBenAchour:我明白是什么让你感到困惑。投票决定重新开放。

标签: c# .net-core


【解决方案1】:

对于这种情况,您可以使用 linqKit。 它具有您在示例代码中使用的完全相同的 And() 函数。

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 2011-06-26
    • 1970-01-01
    • 2012-04-15
    • 2016-12-30
    • 2023-02-14
    • 2015-04-16
    • 2021-07-11
    相关资源
    最近更新 更多