我需要以下通用方法才能执行 LINQ Where 查询:
public static List<T> GetItems<T>(Guid parentId = new Guid()) where T : new()
{
var db = new SQLiteConnection(_dbPath);
List<T> result;
if (parentId != Guid.Empty)
{
result = db.Table<T>().Where(i => i.ParentId.Equals(parentId)).ToList();
}
else
{
result = db.Table<T>().ToList();
}
db.Close();
return result;
}
编译器不喜欢下面这行
result = db.Table<T>().Where(i => i.ParentId.Equals(parentId)).ToList();
error: cannot resolve 'ParentId'
是否可以在 LINQ 查询中以这种方式使用泛型?请注意,类型 T 的对象将始终具有 ParentId 属性。
最佳答案
您应该使用一些包含所需值的接口(interface)具体化 T
参数。此外,您应该将此接口(interface)添加到包含此字段的所有类型或其类的基类型。
public interface IHierarchy
{
public Guid ParentId { get; }
}
public static List<T> GetItems<T>(Guid parentId = new Guid())
where T : IHierarchy, new()
{
var db = new SQLiteConnection(_dbPath);
List<T> result;
if (parentId != Guid.Empty)
{
result = db.Table<T>().Where(i => i.ParentId.Equals(parentId)).ToList();
}
else
{
result = db.Table<T>().ToList();
}
db.Close();
return result;
}
如果您有两种类型的实体,并且第一种包含必需的值而第二种不包含,那么您可以为这种情况使用两个重载。
关于c# - 如何使用 LINQ Where 获取泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48188366/