Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get a Guid? via linq

Tags:

c#

.net

linq

I need to get the id value from Table1 which is a Guid. This query can return a null also. So I started with following

Guid? SomeID = from R in Table1
    join P in Table2
    on R.Id equals P.Id2
    where R.Name == 'blah blah' 
    select R.Id;

But I get following compilation error.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Guid?'

Changing Guid? to Guid didn't help.

Guid SomeID = from R in Table1
    join P in Table2
    on R.Id equals P.Id2
    where R.Name == 'blah blah' 
    select R.Id;

as now I get following error.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Guid'

What am I doing wrong?

like image 568
crazy novice Avatar asked Oct 31 '25 23:10

crazy novice


2 Answers

Your query returns all matching guids and it has type IQueryable<Guid?>

IQueryable<Guid?> guids = 
    from R in Table1
    join P in Table2
    on R.Id equals P.Id2
    where R.Name == 'blah blah' 
    select R.Id;

If you need one guid, use First, Single, FirstOrDefault, or SingleOrDefault

Guild? guid = guids.FirstOrDefault();

Or in single statement:

Guid? guid = Table1.Where(R => R.Name == "blah")
                   .Join(Table2, R => R.Id, P => P.Id2, (R,P) => R.Id)
                   .FirstOrDefault();

Mixed syntax (unfortunately there is no equivalent for FirstOrDefault operator in query syntax):

Guid? guid =  (from R in Table1
               join P in Table2
               on R.Id equals P.Id2
               where R.Name == 'blah blah' 
               select R.Id).FirstOrDefault();
like image 181
Sergey Berezovskiy Avatar answered Nov 03 '25 14:11

Sergey Berezovskiy


Enumerable.Select returns an IEnumerable<T> which is a sequence, so normally multiple items. If you want the first item use First or (if it can be empty) FirstOrDefault:

Guid? SomeID = (from R in Table1
               join P in Table2
               on R.Id equals P.Id2
               where R.Name == 'blah blah' 
               select R.Id).First();
like image 21
Tim Schmelter Avatar answered Nov 03 '25 14:11

Tim Schmelter