我开始学习.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 Ramanathan