使用linq从具有字段名称和字段值的列表中进行选择(类似于select命令)

时间:2015-10-18 09:30:33

标签: c# sql-server linq entity-framework-6

我想从动态列表中选择列表字段名称为例如' SecName'并且SecName值等于例如' xxx', 我知道如何在sql中创建它,但我想创建并使用它与实体框架。 就像在sql中执行String一样。 我怎样才能在实体框架和linq中实现它。 它应该是这样的

var lst=_efmodel.Tables.where(x=>x.fieldname=="SecName" && x.value=="xxx").tolist();

我正在寻找通过传递两个字符串来过滤我的列表的语法,第一个字符串应该是属性Name而另一个应该是该属性值。

2 个答案:

答案 0 :(得分:2)

搜索后我找到了答案,答案是:

     public class SearchField
    {
        public string Name { get; set; }
        public string @Value { get; set; }
        //public string Operator { get; set; }

        public SearchField(string Name, string @Value)
        {
            this.Name = Name;
            this.@Value = @Value;
            //Operator = "=";
        }
    }
    public class FilterLinq<T>
    {
        public static Expression<Func<T, Boolean>> GetWherePredicate(params SearchField[] SearchFieldList)
        {

            //the 'IN' parameter for expression ie T=> condition
            ParameterExpression pe = Expression.Parameter(typeof(T), typeof(T).Name);

            //combine them with and 1=1 Like no expression
            Expression combined = null;

            if (SearchFieldList != null)
            {
                foreach (var fieldItem in SearchFieldList)
                {
                    //Expression for accessing Fields name property
                    Expression columnNameProperty = Expression.Property(pe, fieldItem.Name);


                    //the name constant to match 
                    Expression columnValue = Expression.Constant(fieldItem.Value);

                    //the first expression: PatientantLastName = ?
                    Expression e1 = Expression.Equal(columnNameProperty, columnValue);

                    if (combined == null)
                    {
                        combined = e1;
                    }
                    else
                    {
                        combined = Expression.And(combined, e1);
                    }
                }
            }

            //create and return the predicate
            if (combined != null) return Expression.Lambda<Func<T, Boolean>>(combined, pe);
            return null;
        }

    }

并像这样使用它:

var lst = _efmodel.Count(2015).AsQueryable()
                                    .Where(
          FilterLinq<PazTedad_Result>.GetWherePredicate(
          new SearchField("FieldName", "FieldValue"))).ToList();

答案 1 :(得分:0)

代码必须是这样的吗?

var lst=_efmodel.Table.Where(x => x.fieldname == <SomeValue>).ToList();