【发布时间】:2014-10-20 11:11:49
【问题描述】:
我正在使用 .NET 开始我的旅程,我需要一些帮助。
我会举例说明我的情况,我有什么,我需要做什么,但我不知道该怎么做。
所以我有这样的课
public class Ban
{
public int ID { get; set; }
public string Nick { get; set; }
public string IP { get; set; }
public string GroupName { get; set; }
}
和变量 bans 是 IQueryable
然后在签名方法中
public IEnumerable<Ban> FindBans(Ban filter);
我需要搜索那个 bans 变量;
我现在如何搜索
public IEnumerable<Ban> FindBans(Ban filter)
{
var bans = GetBansQueryable();
if (!string.IsNullOrWhiteSpace(filter.GroupName))
{
bans = bans.Where(b => b.GroupName == filter.GroupName);
}
if (!string.IsNullOrWhiteSpace(filter.Nick))
{
bans = bans.Where(b => b.Nick == filter.Nick);
}
if (!string.IsNullOrWhiteSpace(filter.IP))
{
bans = bans.Where(b => b.IP == filter.IP);
}
return bans.AsEnumerable();
}
使用 AND 进行过滤。 SQL查询部分会是这样的
... WHERE group_name = 'abc' AND nick = 'def' AND ip = 'ghi';
我需要的是
... WHERE group_name = 'abc' AND (nick = 'def' OR ip = 'ghi');
所有这些都需要是动态的(如果我们不通过 GroupName 就不要过滤它等) 除了手动制作这种动态之外,我不知道如何实现这一点
if (!string.IsNullOrWhiteSpace(filter.GroupName) &&
string.IsNullOrWhiteSpace(filter.Nick) &&
string.IsNullOrWhiteSpace(filter.IP))
{
bans = bans.Where(b => b.GroupName == filter.GroupName);
}
else if (!string.IsNullOrWhiteSpace(filter.GroupName) &&
!string.IsNullOrWhiteSpace(filter.Nick) &&
string.IsNullOrWhiteSpace(filter.IP))
{
bans = bans.Where(b => b.GroupName == filter.GroupName && b.Nick == filter.Nick);
}
else if (!string.IsNullOrWhiteSpace(filter.GroupName) &&
!string.IsNullOrWhiteSpace(filter.Nick) &&
!string.IsNullOrWhiteSpace(filter.IP))
{
bans = bans.Where(b => b.GroupName == filter.GroupName && (b.Nick == filter.Nick || b.IP == filter.IP));
}
以此类推...现在将另一个变量添加到 Ban。
【问题讨论】:
-
试试这个:
.Where((b => b.GroupName =="abc") && b.(nick =="def")||b.ip=="ghi") -
@Thirisangu:这不处理空情况,就像在当前代码中一样。我认为SQL语句并不完全正确。
-
我认为 PredicateBuilder 可以帮助你。 albahari.com/nutshell/predicatebuilder.aspx