C#Linq列名作为变量

C#Linq列名作为变量,c#,linq,entity-framework,C#,Linq,Entity Framework,我有一个表,我想在其中对变量列进行查询。 比如: 假设我想寻找一家供应商,那么会是: var s1 = (from c in db.Components where (c.supplier == "abc") select new {c.id, c.supplier}); 有没有办法将列名作为变量传递?一个很好的方法是使用 比如: var s1 = (from c in db.Components where(column + "=" + va

我有一个表,我想在其中对变量列进行查询。 比如:

假设我想寻找一家供应商,那么会是:

var s1 = (from c in db.Components
          where (c.supplier == "abc")
          select new {c.id, c.supplier});
有没有办法将列名作为变量传递?

一个很好的方法是使用

比如:

var s1 = (from c in db.Components
    where(column + "=" + value)
    select new {c.id, **column**});

我想这个例子很有用

 void BindGridTypeSafe()
    {
        NorthwindDataContext northwind = new NorthwindDataContext();

        var query = from p in northwind.Products
                    where p.CategoryID == 3 && p.UnitPrice > 3
                    orderby p.SupplierID
                    select p;

        GridView1.DataSource = query;
        GridView1.DataBind();
    }

    void BindGridDynamic()
    {
        NorthwindDataContext northwind = new NorthwindDataContext();

        var query = northwind.Products
                             .Where("CategoryID = 3 AND UnitPrice > 3")
                             .OrderBy("SupplierID");

        GridView1.DataSource = query;
        GridView1.DataBind();
    }

简短的回答是添加library System.Linq.Dynamic作为参考,并执行以下操作:

string columnName = "Supplier";
var s1 = Suppliers
    .Where(String.Format("{0} == \"abc\"", columnName))
    .Select(new {c.id, c.supplier};
以下是动态Linq的完整工作示例,其中列名是一个参数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;

public class Program
{
    public static void Main()
    {
        var lstContacts = new List<Contact>{
            new Contact{Id = 1, Active = true, Name = "Chris"}, 
            new Contact{Id = 2, Active = true, Name = "Scott"}, 
            new Contact{Id = 3, Active = true, Name = "Mark"}, 
            new Contact{Id = 4, Active = false, Name = "Alan"}};

        string columnName = "Active";
        List<Contact> results = lstContacts.Where(String.Format("{0} == true", columnName)).ToList();

        foreach (var item in results)
        {
            Console.WriteLine(item.Id.ToString() + " - " + item.Name.ToString());
        }
    }
}

public class Contact
{
    public int Id
    {
        get;
        set;
    }

    public bool Active
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Linq.Dynamic;
公共课程
{
公共静态void Main()
{
var lstContacts=新列表{
新联系人{Id=1,Active=true,Name=“Chris”},
新联系人{Id=2,Active=true,Name=“Scott”},
新联系人{Id=3,Active=true,Name=“Mark”},
新联系人{Id=4,Active=false,Name=“Alan”};
string columnName=“活动”;
列表结果=lstContacts.Where(String.Format(“{0}==true”,columnName)).ToList();
foreach(结果中的var项目)
{
Console.WriteLine(item.Id.ToString()+“-”+item.Name.ToString());
}
}
}
公共类联系人
{
公共整数Id
{
得到;
设置
}
公共图书馆
{
得到;
设置
}
公共字符串名
{
得到;
设置
}
}

你可以尝试一下这个

我正在恢复这个旧线程,因为我今天必须用ASP.NET Core 2.2解决这个问题。我使用NuGet包创建了以下扩展方法,如果您需要检查多个给定的字符串值是否包含在多个给定的列中,该方法将非常有效

public static IQueryable<TEntity> WhereContains<TEntity>(
    this IQueryable<TEntity> query,
    string field,
    string value,
    bool throwExceptionIfNoProperty = false,
    bool throwExceptionIfNoType = false)
    where TEntity : class
{
    PropertyInfo propertyInfo = typeof(TEntity).GetProperty(field);
    if (propertyInfo != null)
    {
        var typeCode = Type.GetTypeCode(propertyInfo.PropertyType);
        switch (typeCode)
        {
            case TypeCode.String:
                return query.Where(String.Format("{0}.Contains(@0)", field), value);
            case TypeCode.Boolean:
                var boolValue = (value != null
                    && (value == "1" || value.ToLower() == "true"))
                    ? true
                    : false;
                return query.Where(String.Format("{0} == @0", field), boolValue);
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
                return query.Where(String.Format("{0}.ToString().Contains(@0)", field), value);

            // todo: DateTime, float, double, decimals, and other types.

            default:
                if (throwExceptionIfNoType)
                    throw new NotSupportedException(String.Format("Type '{0}' not supported.", typeCode));
                break;
        }
    }
    else
    {
        if (throwExceptionIfNoProperty)
            throw new NotSupportedException(String.Format("Property '{0}' not found.", propertyInfo.Name));
    }
    return query;
}
公共静态IQueryable,其中包含(
这是一个易懂的问题,
字符串字段,
字符串值,
bool throweExceptionIfNoProperty=false,
bool throwExceptionIfNoType=false)
地点:班级
{
PropertyInfo PropertyInfo=typeof(tenty).GetProperty(field);
if(propertyInfo!=null)
{
var typeCode=Type.GetTypeCode(propertyInfo.PropertyType);
开关(类型代码)
{
大小写类型代码。字符串:
返回query.Where(String.Format(“{0}.Contains(@0)”,field),value);
大小写类型代码。布尔值:
变量布尔值=(值!=null)
&&(value==“1”| | value.ToLower()==“true”))
真的吗
:假;
返回query.Where(String.Format(“{0}=@0”,field),布尔值);
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
案例类型代码.UInt16:
案例类型代码.UInt32:
案例类型代码.UInt64:
返回query.Where(String.Format(“{0}.ToString().Contains(@0)”,field),value);
//todo:日期时间、浮点、双精度、小数和其他类型。
违约:
if(ThroweExceptionIfNotype)
抛出新的NotSupportedException(String.Format(“不支持类型“{0}”,typeCode));
打破
}
}
其他的
{
如果(通过ExceptionIfNoProperty)
抛出新的NotSupportedException(String.Format(“未找到属性“{0}”,propertyInfo.Name));
}
返回查询;
}
该代码可以与.NETStandard/.NETCore(使用上述包)一起使用,也可以与ASP.NET 4.x(使用包)一起使用


有关WhereContains扩展方法和完整用例信息的更多信息,请查看我的博客。

请查看并在此处发布新问题之前进行适当搜索,因为这会影响您的回复。您也可以使用thx作为示例,我尝试过,但它引发了一个异常。我发现因为我使用entityframework,所以必须写it.COLUMNNAME(it.supplier)。这解决了我使用动态linq的问题。谢谢!这是通过添加Linq.dynamespace来使用的。与上面的示例相同,用户提到使用entityframework,并且必须编写它。COLUMNNAME
public static IQueryable<TEntity> WhereContains<TEntity>(
    this IQueryable<TEntity> query,
    string field,
    string value,
    bool throwExceptionIfNoProperty = false,
    bool throwExceptionIfNoType = false)
    where TEntity : class
{
    PropertyInfo propertyInfo = typeof(TEntity).GetProperty(field);
    if (propertyInfo != null)
    {
        var typeCode = Type.GetTypeCode(propertyInfo.PropertyType);
        switch (typeCode)
        {
            case TypeCode.String:
                return query.Where(String.Format("{0}.Contains(@0)", field), value);
            case TypeCode.Boolean:
                var boolValue = (value != null
                    && (value == "1" || value.ToLower() == "true"))
                    ? true
                    : false;
                return query.Where(String.Format("{0} == @0", field), boolValue);
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
                return query.Where(String.Format("{0}.ToString().Contains(@0)", field), value);

            // todo: DateTime, float, double, decimals, and other types.

            default:
                if (throwExceptionIfNoType)
                    throw new NotSupportedException(String.Format("Type '{0}' not supported.", typeCode));
                break;
        }
    }
    else
    {
        if (throwExceptionIfNoProperty)
            throw new NotSupportedException(String.Format("Property '{0}' not found.", propertyInfo.Name));
    }
    return query;
}