Linq表达式where子句与泛型类型 [英] Linq expression where clause with generic type
问题描述
在我的数据访问层中,我使用以下Lambda表达式调用GET方法:
public List< T>获取< T>()其中T:class
{
var list = Context.Set< T>()。ToList()。Distinct()。其中(x => x.Content_type == 测试);
返回列表;
}
但是出错
无法解析符号Content_type
我该如何解决这个问题?
正如@tchelidze所说,你可以在你的函数中设置一个where子句来指定一个类型,如下所示:
public List< T>获取< T>()其中T:IYourCommonInterface
{
var list = Context.Set< T>()。其中(x => x.Content_type ==Test)。Distinct .ToList();
返回列表;
}
但是,如果您需要全面通用,您可以将选择器添加到您的像这样的功能:
public List< T>获取< T>(Func< T,object> selector)其中T:class
{
var list = Context.Set< T>()其中(x => selector(x)== 测试)个不同的()ToList()。;
返回列表;
}
并像这样使用它:
Get(x => x.Content_type);
另外,如果您想进一步了解,您可以传递整个条件:
public List< T> ()函数,其中T:class
{
var list = Context.Set< T>()。其中(condition).Distinct()。ToList() ;
返回列表;
}
并像这样使用它:
Get(x => x.Content_type ==test);
希望它有帮助。
In my Data access layer, I am calling the GET method with the following Lambda expression :
public List<T> Get<T>() where T : class
{
var list = Context.Set<T>().ToList().Distinct().Where(x => x.Content_type == "Test");
return list;
}
But getting error
"Cannot resolve symbol Content_type"
How can i resolve this issue ?
The problem is that Content_type
is not a part of T class because it's just a class.
As @tchelidze says, you can set a where clause on your function to specify a type, like this :
public List<T> Get<T>() where T : IYourCommonInterface
{
var list = Context.Set<T>().Where(x => x.Content_type == "Test").Distinct().ToList();
return list;
}
But if you need to be totaly generic, you can add a selector to your function like this :
public List<T> Get<T>(Func<T, object> selector) where T : class
{
var list = Context.Set<T>().Where(x => selector(x) == "Test").Distinct().ToList();
return list;
}
And use it like that :
Get(x => x.Content_type);
Also, if you want to go further, you can pass the entire condition :
public List<T> Get<T>(Func<T, bool> condition) where T : class
{
var list = Context.Set<T>().Where(condition).Distinct().ToList();
return list;
}
And use it like this :
Get(x => x.Content_type == "test");
Hope it helps.
这篇关于Linq表达式where子句与泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!