gpt4 book ai didi

c# - MVC LINQ 测试存储库

转载 作者:行者123 更新时间:2023-11-30 22:13:24 25 4
gpt4 key购买 nike

我正在为依赖注入(inject)创建一个测试存储库,下面有我的测试方法。

private List<object> records;

public IList<T> GetFiltered<T>(Expression<Func<T, bool>> action = null) where T : class
{
return ((List<T>)records).Where(action).ToList();
}

我基本上想返回一个经过过滤的记录列表,其中“操作”条件为真。

我得到以下错误

Error 2 Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.IQueryable'

请帮忙。

最佳答案

您需要使用 IEnumerable<T> Where 的版本期望 Func<T, bool>不是IQueryable<T>这需要 Expression例如

public IList<T> GetFiltered<T>(Func<T, bool> action = null) where T : class
{
return ((List<T>)records).Where(action).ToList();
}

此外,List<object>无法转换为 List<T>我的建议是使外部类也通用,即

public class MyContainer<T>
{
private List<T> records;

public IList<T> GetFiltered(Func<T, bool> action = null) where T : class
{
return records.Where(action).ToList();
}
}

关于c# - MVC LINQ 测试存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19182267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com