Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在lambda表达式中使用变量字段名_C#_Linq_Lambda - Fatal编程技术网

C# 在lambda表达式中使用变量字段名

C# 在lambda表达式中使用变量字段名,c#,linq,lambda,C#,Linq,Lambda,我正在尝试在我的应用程序中创建一些筛选,用户将单击单元格并根据该单元格值筛选表。。。到目前为止,我有这个 int c = this.dataGridView1.CurrentCell.ColumnIndex; int r = this.dataGridView1.CurrentCell.RowIndex; string s = this.dataGridView1.Rows[r].Cells[c].Value.ToString(); string n = this.dataGridView1.C

我正在尝试在我的应用程序中创建一些筛选,用户将单击单元格并根据该单元格值筛选表。。。到目前为止,我有这个

int c = this.dataGridView1.CurrentCell.ColumnIndex;
int r = this.dataGridView1.CurrentCell.RowIndex;
string s = this.dataGridView1.Rows[r].Cells[c].Value.ToString();
string n = this.dataGridView1.Columns[c].DataPropertyName.ToString();

weblogEntities dbEntities = new weblogEntities();
this.Text = dbEntities.Database.Connection.ConnectionString.ToString();
var ds = dbEntities.tbl_weblog.Where(m => n == s).ToList();
dataGridView1.DataSource = ds; 
但由于lambda表达式的原因,我的筛选不起作用。有人能告诉我如何在我的linq中包含正确的lambda吗

说明: 我试图做的是
(m=>m.field\u name==value)
其中
m.field\u name
应该是
n
,在执行过滤器之前我不知道这是什么,值参数是
s
,您可以使用:

另一种方法是构建查询表达式。下面是一个扩展方法,它构建谓词表达式,用于按名称按属性的某个值筛选源:

public static IQueryable<T> Where<T>(this IQueryable<T> source, 
   string propertyName, object value)
{
    var parameter = Expression.Parameter(typeof(T), "t");
    var property = Expression.PropertyOrField(parameter, propertyName);
    var body = Expression.Equal(property, Expression.Constant(value));
    var expr = Expression.Lambda<Func<T, bool>>(body, parameter);
    return source.Where(expr);
}

注意:在这种情况下,不要将值转换为字符串。如果您有整数值,那么应该将其作为整数传递。

我认为您需要清楚地查看代码

这条线是什么

var ds = dbEntities.tbl_weblog.Where(m => n == s).ToList();
是有效地做是

var b = n == s;
// this line will include all if n==s otherwise include none
var ds = dbEntities.tbl_weblog.Where(m => b).ToList();
未检查lambda表达式中的
m
变量

恐怕没有足够的信息给你更多的提示。您可能想考虑将变量命名为更可读的(例如,代码> CulnQuale而不是<代码> c>代码>

< p>尝试使用::

var ds = dbEntities.tbl_weblog.Where(m => n == s).ToList();
dataGridView1.DataSource = ds; 

这可能会有帮助。

过滤器应该是什么?如果n==s,则得到整个表,如果不是,则什么也得不到。你想过滤哪一列?我想你需要比较一下“m”的一些属性。你能用英语写下你的where子句应该是什么吗?因为你不清楚你想达到什么目的
var b = n == s;
// this line will include all if n==s otherwise include none
var ds = dbEntities.tbl_weblog.Where(m => b).ToList();
var ds = dbEntities.tbl_weblog.Where(m => n == s).ToList();
dataGridView1.DataSource = ds;