nhat
nhat

Reputation: 1169

Errors in using LINQ with IList

I'm trying to use LINQ and I keep getting this error message:

Operator '<' cannot be applied to operands of type 'Ilistprac.Location' and 'int'

I tried an override but I get an error message:

'Ilistprac.Location.ToInt()': no suitable method found to override

All the IList interfaces are implemented with the IEnurmerable too (just not listed here unless someone wants me to).

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

 }

Upvotes: 1

Views: 290

Answers (4)

devgeezer
devgeezer

Reputation: 4189

Another alternative is to create an implicit conversion operator on the Location class like so:

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

With the above, the compiler will try to call this conversion operator on Location instances when comparing them with int's.

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19030

You either want to compare n.testNumber or you need to overload the < operator in the Location class so you can actually compare it to an 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;
    }
 }

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460228

You probably want to compare n.testNumber with 2

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

Edit: if you want to overload operators, have a look at this tutorial:

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

Upvotes: 3

Ian Mercer
Ian Mercer

Reputation: 39277

Try

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

Upvotes: 1

Related Questions