如何解决where子句项中的泛型谓词?
我面对3条错误where子句“ _list.Where
错误1
“System.Collections.Generic.List
错误2实例参数:无法从“System.Collections.Generic.List”转换
错误3参数2:无法从'System.Func转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FuncMetodunuTaniyalim3
{
public class Search<T> where T : class
{
private List<DataModel.Customer> _list;
public Search()
{
_list = new List<DataModel.Customer>();
}
public int Find(Func<T, bool> whereClause)
{
return _list.IndexOf(_list.Where<T>(whereClause).FirstOrDefault<T>());
}
}
//Repository
public class DataModel
{
private IEnumerable<Customer> customers;
public List<Customer> Customers
{
get { return customers.ToList(); }
}
public DataModel()
{
customers = new[] { new Customer(){ Id=1, Name="cbfghg", SurName="hfh", Age=29, Dept=0, Income=100},
new Customer(){ Id=2, Name="hfghfhf", SurName="erhfghfhfhem", Age=0,Dept=45, Income=300},
new Customer(){ Id=3, Name="hgfhgfhf", SurName="balhfghgfhfgh", Age=33, Dept=20, Income=150}};
}
//Model
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string SurName { get; set; }
public int Age { get; set; }
public int Income { get; set; }
public int Dept { get; set; }
public Customer()
{
}
}
}
}
您的搜索类包含一个List<Customer>
。 可能你打算使用List<T>
:
public class Search<T> where T : class
{
private List<T> _list;
public Search()
{
_list = new List<T>();
}
public int Find(Func<T, bool> whereClause)
{
return _list.IndexOf(_list.Where<T>(whereClause).FirstOrDefault<T>());
}
}
你的列表是一个List<DataModel.Customer>
,而你的谓词是一个Func<T, bool>
。 将谓词的类型更改为Func<DataModel.Customer, bool>
或将您的列表类型更改为List<T>
。
你不能这样做,因为List<DataModel.Customer>
实现IEnumerable<DataModel.Customer>
请看方法文档:http://msdn.microsoft.com/en-us/library/bb534803.aspx也许你想要_list作为List<T>
在那里?