LINQ Where 子句中的 If 条件

发布于 2024-09-18 17:03:55 字数 52 浏览 4 评论 0原文

使用 Linq,我可以在 Where 扩展方法中使用条件语句吗?

With Linq, can I use a conditional statement inside of a Where extension method?

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

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

发布评论

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

评论(9

野鹿林 2024-09-25 17:03:55
var query = someList.Where(a => (someCondition)? a == "something" : true);

因此,如果 'someCondition' 为 false,则将跳过 'Where'。

var query = someList.Where(a => (someCondition)? a == "something" : true);

so, if 'someCondition' is false, 'Where' will be skipped.

╰つ倒转 2024-09-25 17:03:55

是的,您可以喜欢:

var query = someList.Where(a => a == "something");
if (condition)
{
    query = query.Where(b => b == "something else");
}
var result = query.ToList();

因为 Where 正在生成 IQueryable,因此执行会推迟到我的示例中的 ToList,以便您可以链接 只要你想要的,就在一起,然后在通过所有条件后执行它。

Yes you can like:

var query = someList.Where(a => a == "something");
if (condition)
{
    query = query.Where(b => b == "something else");
}
var result = query.ToList();

Because Where is producing an IQueryable, the execution is deferred until the ToList in my example so you can chain Wheres together as much as you want and then just execute it after you have passed all your conditions.

蒗幽 2024-09-25 17:03:55

中使用 WhereIf 扩展方法,

在 linq示例

if (SearchControlMain.PostingID.HasValue) 
    query = query.Where(q => q.PostingID == SearchControlMain.PostingID);

而不是上面的示例,请使用下面的

query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);

LINQWhereIf扩展方法

LINQ to SQLWhere子句可选条件

Make use of WhereIf extenstion method avaialbe in linq

Example

if (SearchControlMain.PostingID.HasValue) 
    query = query.Where(q => q.PostingID == SearchControlMain.PostingID);

instead of above go for the below

query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);

LINQ WhereIf Extension Method

LINQ to SQL Where Clause Optional Criteria

梦过后 2024-09-25 17:03:55

不确定这是否合适,但它非常有用,您可以非常方便地将 if 与条件 where 子句一起使用:

 var r = (from p in productinfo.tblproduct
                     where p.Accountid == accountid
                     select p);

            if (uuf1 != null)
                r = r.Where(p => p.UnitUserField1 == uuf1);

            if (uuf2!= null)
                r = r.Where(p => p.UnitUserField2 == uuf2);

因此,where 子句将根据 UUF1 或 UUF2 中的内容进行修改,即您可能只有带信息的 UUF1,在这种情况下它将接受并忽略 UUF2 where 子句,您可能同时拥有两个,其中它将同时接受两个,或者您可能在 UUF1 或 2 中没有任何内容,并且您的 where 子句将仅将 accountid 作为 where 子句。

Not sure if this is appropriate but it is quite useful, you can use ifs quite handily with conditional where clauses:

 var r = (from p in productinfo.tblproduct
                     where p.Accountid == accountid
                     select p);

            if (uuf1 != null)
                r = r.Where(p => p.UnitUserField1 == uuf1);

            if (uuf2!= null)
                r = r.Where(p => p.UnitUserField2 == uuf2);

So the where clause will be amended according to what is in UUF1 or UUF2 i.e. you might have only UUF1 with info, in which case it will take that and ignore the UUF2 where clause, you might have both in which it will take both or you might not have anything in UUF1 or 2 and your where clause will just take the accountid as the where clause.

潦草背影 2024-09-25 17:03:55

就我而言,有两个“条件”取决于搜索键,所以我这样做了:

    var query = db.Package.Include("SomeThing")
    .Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
    .Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
    ...

In my case there were two "conditional" where depending on search keys, so I did:

    var query = db.Package.Include("SomeThing")
    .Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
    .Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
    ...
带上头具痛哭 2024-09-25 17:03:55
from item in items
where condition1
&& (condition2 ? true : condition3)
select item

这就是如何使用 noob Linq 语法来做到这一点。
仅当条件 2 为假时才应用条件 3。
如果条件2为真,你实际上是在做 && true 对 where 子句没有影响。

所以它本质上是这样做的:

if(condition2)
{
    from item in items
    where condition1
    select item
else
{
    from item in items
    where condition1
    && condition3
    select item
}
from item in items
where condition1
&& (condition2 ? true : condition3)
select item

This is how can you can do it with the noob Linq syntax.
This applies the condition3 only if condition2 is false.
If condition2 is true, you are essentially doing && true which has no effect on the where clause.

So it is essentially doing this:

if(condition2)
{
    from item in items
    where condition1
    select item
else
{
    from item in items
    where condition1
    && condition3
    select item
}
嘿嘿嘿 2024-09-25 17:03:55

我遇到过这样的情况,我必须检查列表本身是否为空。这就是我所做的。

items = from p in items
        where p.property1 != null   //Add other if conditions
        select p;

// Use items the way you would use inside the if condition

但正如凯尔西指出的那样,这也行得通——

items = items.Where(a => a.property1 != null);

I had a scenario like this where I had to check for null within the list itself. This is what I did.

items = from p in items
        where p.property1 != null   //Add other if conditions
        select p;

// Use items the way you would use inside the if condition

But as Kelsey pointed out this would work too -

items = items.Where(a => a.property1 != null);
葬花如无物 2024-09-25 17:03:55

我不确定问题是什么,但可能的答案可能是:

是的,

list.Where(item => { if (Foo(item)) return true; else return false; });

尽管如此,这会是一种说简单事情的复杂方式。

I'm not sure what the question is, but a possible answer could be:

Yes,

list.Where(item => { if (Foo(item)) return true; else return false; });

It would be a complicated way of saying something simple, though.

离旧人 2024-09-25 17:03:55

就我而言,我想保留符合我标准的元素,并记录不符合我标准的元素,而无需多次迭代。

var merchantsWithLocations = allMerchants.Where(m =>
    {
        if (m.Locations?.Any() != true)
        {
            _logger.Log("Merchant {merchantId} has no locations", m.Id);
            return false;
        }
        return true;
    };

每当您想要对每个元素执行副作用(例如日志记录)时,将 lambda 分解到语句主体中就可以轻松推理。

In my case, I wanted to keep the elements which met my criteria and log the ones that didn't without iterating multiple times.

var merchantsWithLocations = allMerchants.Where(m =>
    {
        if (m.Locations?.Any() != true)
        {
            _logger.Log("Merchant {merchantId} has no locations", m.Id);
            return false;
        }
        return true;
    };

Any time you want to do a side-effect per element (such as logging), breaking out the lambda into a statement body makes it easy to reason about.

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