我有此代码:
switch (Settings.cvm)
{
case CVM.IncludeHidden:
return new SelectedPhrases()
{
ps = ps,
psNoa = psNoa
};
case CVM.ExcludeHidden:
return new SelectedPhrases()
{
ps = ps.Where(x => x.Hidden == false).ToList(),
psNoa = psNoa.Where(x => x.Hidden == false).ToList()
};
case CVM.Hidden:
return new SelectedPhrases()
{
ps = ps.Where(x => x.Hidden == true).ToList(),
psNoa = psNoa.Where(x => x.Hidden == true).ToList()
};
case CVM.Favorites:
return new SelectedPhrases()
{
ps = ps.Where(x => x.Favorite == true).ToList(),
psNoa = psNoa.Where(x => x.Favorite == true).ToList()
};
default:
return null;
}
有什么方法可以让开关只返回where子句,而不是从开关内部返回:
x => x.Hidden == false
然后在开关之后将where子句添加到变量ps和psNoa中?
答案 0 :(得分:1)
您可以将委派Func用于where子句。然后将委托放入Where()方法。
void Main()
{
var persons = new []
{
new Person { Id = 1, Name = "Alice", Active = true },
new Person { Id = 2, Name = "Bob", Active = false },
new Person { Id = 3, Name = "Charlie", Active = true },
};
Func<Person, bool> whereClause;
var isActive = true; // change the value here
if (isActive)
whereClause = x => x.Active == true;
else
whereClause = x => x.Active == false;
var query = persons.Where(whereClause);
query.Dump();
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
}
答案 1 :(得分:0)
是的,确实可以
在开关中做
case zzz:
ps = ps.Where(xxxxx).ToList();
psnoa = psnoa.Where(yyyy).ToList();
break;
....
然后切换。
return new SelectedPhrases()
{
ps.ToList(),
psNoa.ToList()
};
关键是您可以逐步进行LINQ操作的管道。 注意-最好将所有内容都保留为IEnuemrable而不是List。这样会将评估推迟到最后