2012-04-13 62 views
1

我试图使用LINQ和我不断收到此错误信息:错误使用LINQ与IList的

操作“<”不能应用于类型“Ilistprac.Location”和“廉政”的操作数

我试图超驰,但我得到的错误消息:

'Ilistprac.Location.ToInt()':发现重写

没有合适的方法

所有的IList接口都是用IEnurmerable实现的(除非有人想要,否则这里没有列出)。

class IList2 
{ 
    static void Main(string[] args) 
    { 

    Locations test = new Locations(); 
    Location loc = new Location(); 
    test.Add2(5); 
    test.Add2(6); 
    test.Add2(1); 
    var lownumes = from n in test where (n < 2) select n; 


    } 
} 

public class Location 
{ 
    public Location() 
    { 

    } 
    private int _testnumber = 0; 
    public int testNumber 
    { 
     get { return _testnumber; } 
     set { _testnumber = value;} 
    } 

public class Locations : IList<Location> 
{ 
    List<Location> _locs = new List<Location>(); 

    public Locations() { } 

    public void Add2(int number) 
    { 
     Location loc2 = new Location(); 
     loc2.testNumber = number; 
     _locs.Add(loc2); 
    } 

} 

回答

1

您可能要比较n.testNumber或者您需要在Location类中超载<运算符,以便您实际上可以将其与int进行比较。

public class Location 
{ 
    public Location() 
    { 

    } 

    private int _testnumber = 0; 
    public int testNumber 
    { 
     get { return _testnumber; } 
     set { _testnumber = value;} 
    } 

    public static bool operator <(Location x, int y) 
    { 
     return x.testNumber < y; 
    } 

    public static bool operator >(Location x, int y) 
    { 
     return x.testNumber > y; 
    } 
} 
+0

好酷的工作。谢谢! – nhat 2012-04-13 19:33:50

1

尝试

var lownumes = from n in test where (n.testNumber < 2) select n; 
0

另一种方法是在Location类创建一个隐式转换操作符,像这样:

public class Location 
{ 
    // ... 
    public static implicit operator int(Location loc) 
    { 
     if (loc == null) throw new ArgumentNullException("loc"); 
     return loc.testNumber; 
    } 
} 

通过以上,编译器将尝试将它们与比较时调用此转换操作符上Location实例INT的。