Richard Banks
Richard Banks

Reputation: 2983

Strange Linq issue

What's the difference between the following two? The first 1 works but the 2nd one errors out stating that 'Select' cannot be found. I can't understand why.

1st:

Office Office = 
    cHelper.Offices
           .Where(o => o.IP3rdOctet  == OSHelper.Get3rdOctetOfMyIP())
           .FirstOrDefault();

2nd:

Office Office = 
    from o in cHelper.Offices
                     .Where(o => o.IP3rdOctet == OSHelper.Get3rdOctetOfMyIP())
                     .FirstOrDefault()
    select o;

Upvotes: 0

Views: 592

Answers (2)

Botz3000
Botz3000

Reputation: 39660

This is not an IEnumerable or IQueryable, it is an instance of Office:

cHelper.Offices.Where(o => o.IP3rdOctet 
                == OSHelper.Get3rdOctetOfMyIP()).FirstOrDefault()

You cannot call select on that. Remove the call to FirstOrDefault(), then you will be able to select the results (which will be empty if no items match your criteria).

If you then still need the FirstOrDefault item, then put the query in brackets and append FirstOrDefault() like this:

Office Office = (from o in cHelper.Offices
                 where o.IP3rdOctet == OSHelper.Get3rdOctetOfMyIP()
                 select o).FirstOrDefault();

Upvotes: 2

Aducci
Aducci

Reputation: 26694

select works with an IEnumerable, you are trying to use select after FirstOrDefault

rewrite like this:

Office Office = (from o in cHelper.Offices
                where o.IP3rdOctet == OSHelper.Get3rdOctetOfMyIP()
                select o).FirstOrDefault();

Upvotes: 1

Related Questions