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

查看:25
本文介绍了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();

提前感谢您的帮助!!!

Thanks for the help in advance!!!

推荐答案

嗯,你可以直接放入多个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 以避免 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天全站免登陆