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;