问候Overflowers的名单,生成的LINQ或条款从枚举
我工作的一个应用程序,允许用户生成自定义报告,我有一种情况,我需要生成从一个LINQ或条款枚举值列表。我遇到的问题是我无法看到生成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;
}
}
任何想法?
你就需要自己构建表达式树。如果向您的项目添加新库是一个选项,请查看[PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx),它完全符合您的需求。 –