Linq to SQL:通过 || 聚合
我正在尝试编写一个 Linq 查询,该查询获取名字或姓氏以字符串列表中至少一个字符串开头的所有用户。这用于消息系统中收件人的自动完成。
这是我的第一次天真的尝试:
var users = UserRepository.ALL()
foreach (var part in new [] { 'Ha', 'Ho', 'He' })
{
string part1 = part; // "Copy" since we're coding lazily
users = users.Where(x => x.LastName.StartsWith(part1) ||
x.FirstName.StartsWith(part1));
}
但这不起作用,因为结果变成:
users.Where(a || b).Where(c || d).Where(e || f)...
...而我想要:
users.Where(a || b || c || d || e || f || ...)
我将如何去做呢?
I'm trying to write a Linq query which fetches all users whose first or last name begins with at least one string in a list of strings. This is used for auto-completion of recipients in a messaging system.
This was my first naive attempt:
var users = UserRepository.ALL()
foreach (var part in new [] { 'Ha', 'Ho', 'He' })
{
string part1 = part; // "Copy" since we're coding lazily
users = users.Where(x => x.LastName.StartsWith(part1) ||
x.FirstName.StartsWith(part1));
}
This doesn't work though, as the result becomes:
users.Where(a || b).Where(c || d).Where(e || f)...
...whereas I want:
users.Where(a || b || c || d || e || f || ...)
How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用 2 个集合 - 在您的代码中您正在过滤列表...实际上您需要过滤列表的集合 - 而不是已过滤多次的列表的集合。
一个作为匹配的存储库,另一个在你的循环中
我并不是说这是最优雅的解决方案 - 只是试图指出为什么你的逻辑失败。
你也许可以用 Contains 做一些事情
,只是看不出我的想法
you need to use 2 collections - in your code you are filtering down a list ... really you need the collection of filtered lists - not a collection of a list that has been filtered multiple times.
one as a repository for matches and the other witin your loop
I am not claiming this is the most elegant solution - just simply trying to point at why your logic is failing.
you can probably do something with Contains
just cant see how off the top of my head
当然,我应该使用
Union
...使用 ReSharper 可以将其转换为 Linq 表达式:
...但我可能会使用
foreach
循环这次。 :)Of course, I should use
Union
...Using ReSharper this could be turned into a Linq expression:
...but I'm probably going to go for the
foreach
loop this time. :)此代码对字符串执行此操作。
对于您的
User
类,它看起来像This code does it for strings.
For your
User
class it would look like这是一行行(为了便于阅读而格式化),我相信它会返回您寻求的结果:
它可能不是您正在寻求的有效解决方案,但我希望它能以某种方式帮助您!
编辑:正如 gaearon 指出的那样,如果 'ALL()' 命令返回大量记录,我的第一个解决方案可能非常糟糕。试试这个:
Here is a one-liner (formatted for readability) that I believe returns the result you seek:
It is probably not the efficient solution you were seeking, but I hope it helps you in some way!
EDIT: As gaearon pointed out, if the 'ALL()' command returns a lot of records, my first solution is probably really bad. Try this:
您可以构造一个表达式树:
结果与以下相同:
You can construct an expression tree:
The result is the same as: