我有超过20个字段的表,其中大多数是整数。
如何只选择值大于零的字段?
有时我想选择四个字段,有时十个字段取决于字段值。
var t = db.Salaries.Where(g => g.الرقم == emp_comp_code &&
g.السنة == year && g.الشهر == month).Distinct().ToList().Select(??field value not equal zero??);
答案 0 :(得分:0)
在调用ToList()
var list = db.Salaries.Where(g => g.الرقم == emp_comp_code &&
g.السنة == year && g.الشهر == month).Distinct().ToList();
var type = list.GetType();
var ObjType = list[0].GetType();
var props = objType.GetProperties();
List<string> propNames = new List<string>();
for (var i = 0; i < list.Count; i++)
{
foreach (var property in props)
{
if(prop.PropertyType == typeof(int)){
var value = int.Parse(list[i].GetType().GetProperty(property.Name)
.GetValue(list[i], null)).ToString());
if ((int)value > 0)
{
propNames.Add(property.Name);
}
}
}
}
然后尝试调用'Nicholas Butler'在this描述的以下函数回答:
Func<Data,Data> CreateNewStatement( string fields )
{
// input parameter "o"
var xParameter = Expression.Parameter( typeof( Data ), "o" );
// new statement "new Data()"
var xNew = Expression.New( typeof( Data ) );
// create initializers
var bindings = fields.Split( ',' ).Select( o => o.Trim() )
.Select( o => {
// property "Field1"
var mi = typeof( Data ).GetProperty( o );
// original value "o.Field1"
var xOriginal = Expression.Property( xParameter, mi );
// set value "Field1 = o.Field1"
return Expression.Bind( mi, xOriginal );
}
);
// initialization "new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var xInit = Expression.MemberInit( xNew, bindings );
// expression "o => new Data { Field1 = o.Field1, Field2 = o.Field2 }"
var lambda = Expression.Lambda<Func<Data,Data>>( xInit, xParameter );
// compile to Func<Data, Data>
return lambda.Compile();
}