2012-04-13 56 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的。