如何解决where子句项中的泛型谓词?

时间:2012-11-22 13:21:53

标签: c# c#-4.0 generics func

我面对3条错误的where子句“ _list.Where< T>(whereClause)”如何解决?

错误1
'System.Collections.Generic.List< FuncMetodunuTaniyalim3.DataModel.Customer>'不包含'Where'的定义和最佳扩展方法重载'System.Linq.ParallelEnumerable.Where< TSource>(System.Linq.ParallelQuery< TSource>,System.Func< TSource,int,bool>)'有一些无效的论点
错误2 实例参数:无法从'System.Collections.Generic.List< FuncMetodunuTaniyalim3.DataModel.Customer>'转换到'System.Linq.ParallelQuery< T>'
错误3 参数2:无法从'System.Func< T,bool>'转换到'System.Func< T,int,bool>'


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()
            {

            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您的列表是List<DataModel.Customer>,而您的谓词是Func<T, bool>。将谓词类型更改为Func<DataModel.Customer, bool>或将列表类型更改为List<T>

答案 1 :(得分:1)

您的搜索类包含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>());
    }
}

答案 2 :(得分:0)

你不能这样做,因为List<DataModel.Customer>实现了IEnumerable<DataModel.Customer> 查看方法文档:http://msdn.microsoft.com/en-us/library/bb534803.aspx也许您希望_list为List<T>吗?