问候溢出者,
我正在开发一个允许用户生成自定义报告的应用程序,并且我有一个场景,我需要从枚举值列表中生成 Linq Or 子句。我遇到的问题是我看不到生成 Or 子句的优雅方式。
例如:
//Enumeration of possible 'OR' conditions
public enum Conditions
{
ByAlpha,
ByBeta,
ByGamma
}
//'Entity' I'm querying against.
class ResultObject
{
public bool AlphaValue { get; set; }
public bool BetaValue { get; set; }
public bool GammaValue { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Create list of desired conditions.
//Basically I want this to mimic the query,
// "Show me all of the ResultObjects where the AlphaValue is true or the GammaValue is true".
var conditions = new List<Conditions>
{
Conditions.ByAlpha,
Conditions.ByGamma
};
//Sample collection of objects. This would normally be a collection of EF entities.
var sampleCollection = new List<ResultObject>
{
new ResultObject
{
Name = "Sample 1",
AlphaValue = true,
BetaValue = true,
GammaValue = true,
},
new ResultObject
{
Name = "Sample 2",
AlphaValue = false,
BetaValue = false,
GammaValue = false,
},
new ResultObject
{
Name = "Sample 3",
AlphaValue = true,
BetaValue = false,
GammaValue = true,
}
};
var sampleCollectionQueryable = sampleCollection.AsQueryable();
//This should filter the sampleCollection down to containing only the
//"Sample 3" ResultObject; instead, it filters out all of the ResultObjects.
var query = GenerateOrClause(sampleCollectionQueryable, conditions);
}
static IQueryable<ResultObject> GenerateOrClause(IQueryable<ResultObject> query, List<Conditions> conditions)
{
//This approach generates a series of AND statements, instead I need a series of OR statements
//for each condition.
foreach (var condition in conditions)
{
switch (condition)
{
case Conditions.ByAlpha:
query = query.Where(x => x.AlphaValue);
break;
case Conditions.ByBeta:
query = query.Where(x => x.BetaValue);
break;
case Conditions.ByGamma:
query = query.Where(x => x.GammaValue);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return query;
}
}
有任何想法吗?