Linq中的多个WHERE子句 [英] Multiple WHERE clause in Linq

查看:176
本文介绍了Linq中的多个WHERE子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是LINQ的新手,想知道如何执行多个where子句.这就是我要实现的目标:通过过滤掉某些用户名来返回记录.我尝试了下面的代码,但未按预期工作.

I'm new to LINQ and want to know how to execute multiple where clause. This is what I want to achieve: return records by filtering out certain user names. I tried the code below but not working as expected.

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where ((r.Field<string>("UserName") != "XXXX") || (r.Field<string>("UserName") != "XXXX"))                            
            select r;    

            DataTable newDT = query.CopyToDataTable();

感谢您的提前帮助!

推荐答案

好吧,您可以直接在其中放置多个"where"子句,但我不希望这样做.多个"where"子句以 more 限制性过滤器结尾-我认为您需要一个 less 限制性过滤器.我认为您真的想要:

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" &&
                  r.Field<string>("UserName") != "YYYY"
            select r;

DataTable newDT = query.CopyToDataTable();

请注意&&代替||.如果用户名不是XXXX 并且用户名不是YYYY,则要选择该行.

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

如果您有一个完整的收藏夹,那就更容易了.假设该集合称为ignoredUserNames:

If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where !ignoredUserNames.Contains(r.Field<string>("UserName"))
            select r;

DataTable newDT = query.CopyToDataTable();

理想情况下,您希望将其设置为HashSet<string>,以免Contains调用花费很长时间,但是如果集合足够小,则不会有太大的机会.

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

这篇关于Linq中的多个WHERE子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆