使用LINQ和IList时出错

时间:2012-04-13 19:00:51

标签: linq c#-4.0

我正在尝试使用LINQ,并且我不断收到此错误消息:

  

运营商'<'不能应用于'Ilistprac.Location'和'int'

类型的操作数

我尝试了覆盖,但收到错误消息:

  

'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);
    }

 }

4 个答案:

答案 0 :(得分:3)

您可能想要将n.testNumber与2

进行比较
var lownumes = from n in test where (n.testNumber < 2) select n;

编辑:如果要重载运算符,请查看本教程:

http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

答案 1 :(得分:1)

尝试

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

答案 2 :(得分: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;
    }
 }

答案 3 :(得分:0)

另一种方法是在Location类上创建一个隐式转换运算符,如下所示:

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

通过上述内容,编译器将尝试在Location实例上调用此转换运算符,并将它们与int进行比较。