Linq query result to int?

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 29669 Views - Last Post: 13 July 2012 - 09:56 PM Rate Topic: -----

#1 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Linq query result to int?

Posted 18 March 2011 - 04:00 PM

I have a simple sql table called "Service" that looks like this:

1 Food
2 Rent
3 Child care
4 Transportation
5 Medical
6 Dental

I have written a query which hopefully will return the key when given the name of the service

        var serkey =

           from a in dc.GetTable<Service>()

           where a.ServiceName == lblService.Text

           select a;


If lblService says "Dental", I want serkey to = 6, and I need to use the 6 to update another table.
I'm getting the "Cannot implicitly convert type 'System.Linq.Iqueryable<Service>' to int'


am I going about this the wrong way, or is there a simple way to convert serkey to an int?


Thanks in advance,

Dave

Is This A Good Question/Topic? 0
  • +

Replies To: Linq query result to int?

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: Linq query result to int?

Posted 18 March 2011 - 04:06 PM

The query returns the entire row from the table Service

Instead return the "id"
Something like
var serkey =

   from a in dc.GetTable<Service>()

   where a.ServiceName == lblService.Text

   select a.Id;

Was This Post Helpful? 0
  • +
  • -

#3 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Re: Linq query result to int?

Posted 18 March 2011 - 04:14 PM

View PostAdamSpeight2008, on 18 March 2011 - 04:06 PM, said:

The query returns the entire row from the table Service

Instead return the "id"
Something like
var serkey =

   from a in dc.GetTable<Service>()

   where a.ServiceName == lblService.Text

   select a.Id;


While that is helpful and correct my query (thanks!) it still won't let me turn the result into an int. I've tried changing the 'var' to 'int' and I've tried saying
int sk = serkey
and I've also tried just putting the query into the insert like :
        SerGrant.ServiceKey = from a in dc.GetTable<Service>()

                              where a.ServiceName == lblService.Text

                              select a.ServiceKey; 

Was This Post Helpful? 0
  • +
  • -

#4 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: Linq query result to int?

Posted 18 March 2011 - 04:21 PM

What the type inferred for this
var  whatTypeIsInferredHere = from a in dc.GetTable<Service>()

                      where a.ServiceName == lblService.Text

                      select a.ServiceKey; 

Was This Post Helpful? 0
  • +
  • -

#5 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Re: Linq query result to int?

Posted 18 March 2011 - 04:30 PM

I'm not sure I understand your reply but the SerGrant.ServiceKey portion of

        SerGrant.ServiceKey = from a in dc.GetTable<Service>()

                              where a.ServiceName == lblService.Text

                              select a.ServiceKey; 


is an int field. So I'm trying to return an int from my query and then insert that int into an int field in a different table.
Was This Post Helpful? 0
  • +
  • -

#6 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Re: Linq query result to int?

Posted 18 March 2011 - 04:36 PM

Since adding the
select a.ServiceKey; 


the error has changed to: "Cannot implicitly convert type 'System.Linq.Iqueryable<int>' to int'

so it knows that it's querying an int, but I can't figure out how to use the result.
Was This Post Helpful? 0
  • +
  • -

#7 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon

Reputation: 2298
  • View blog
  • Posts: 9,535
  • Joined: 29-May 08

Re: Linq query result to int?

Posted 18 March 2011 - 04:55 PM

You do know what var means in the context of C#?

It means Statically Inferred Type. (MSDN Doc)

So if you hover the mouse pointer over the variable name whatTypeIsInferredHere, the IDE will tell you the type, the compiler has inferred it to be. (This may need a compile of your project)

This post has been edited by AdamSpeight2008: 18 March 2011 - 04:58 PM

Was This Post Helpful? 0
  • +
  • -

#8 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Linq query result to int?

Posted 18 March 2011 - 05:02 PM

You're selecting a collection. You have to select a single instance.

So, we take your initial query:

var serkey =

   from a in dc.GetTable<Service>()

   where a.ServiceName == lblService.Text

   select a;



Then we need to see if anything is there.

int key;
var first = serkey.FirstOrDefault();
if(first != null)
  key = first.Id;


You should also have an else clause to handle none being found.

If you know for certain that only one or none would be returned, you could use SingleOrDefault instead.

If you know for sure that one, only and always one would be returned, you can skip the if statement, and just use .Single().Id;

You can actually condense your entire query into this:

int id;
var first = dc.GetTable<Service>().FirstOrDefault(a=>a.ServiceName == lblService.Text);
if(first != null)
  id = first.Id;

This post has been edited by insertAlias: 18 March 2011 - 05:04 PM

Was This Post Helpful? 1
  • +
  • -

#9 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Linq query result to int?

Posted 18 March 2011 - 05:07 PM

I frequently use FirstOrDefault or SingleOrDefault. First and Single also exist. FirstOrDefault is the safest, while Single is the most dangerous.

FirstOrDefault shouldn't throw any exceptions.
First can throw an exception when the collection is empty.
SingleOrDefault will throw an exception when there's more than one item in the collection.
Single will throw an exception if the collection is empty, or if there's more than one item. In other words, Single expects there to be one, only one, and always one item in the collection.

The "Default" methods will return the default value for the type the collections are empty. For reference types (classes and nullable structs), the default value is null. For non-nullable types, default values are predefined. For example, the default DateTime is DateTime.MinValue.
Was This Post Helpful? 0
  • +
  • -

#10 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Re: Linq query result to int?

Posted 18 March 2011 - 06:31 PM

Wow, this is great. I haven't tried it yet, but this is good info.

I was getting ready to just cheese out and do a switch/Case to choose which number to use so I could turn it in and be finished, but I wanted to learn how to do this type of query. Unfortunately sometimes it's hard to find solutions using Google. Like this one, most people seem to use this type of query because they want to display a set of data.

Thanks again.
Was This Post Helpful? 0
  • +
  • -

#11 blodzoom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-March 11

Re: Linq query result to int?

Posted 18 March 2011 - 07:09 PM

It worked beautifully!

I didn't bother with error checking to make sure that it returned a value or anything because I know that it will because it's not a real job and nobody's going to change the database.

I plan on coming back to play with this some more, but I have to study for a networking final and I've already spent more time than I should have on this.

You guys are the best.
Was This Post Helpful? 0
  • +
  • -

#12 gerdi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 11-July 12

Re: Linq query result to int?

Posted 11 July 2012 - 03:03 AM

Im a bit of a n00b with all this but While searching for an question to a similar problem ( pretty much the same , I needed a textbox control to link to the tables Id which is an int ) i got to this post

the responses didnt work for me but it pretty much unlined what i need to do and it seems really simple.
basically i just declared a variable with a Parse Int to the textbox control and then passed that variable in the linq.

// Creating variable to change the string into a int for employee ID which is an int in the DB
  var txtboxForEmployeeId = Int32.Parse(txtbxEmployeeId.Text);

// Operational code to find employee to be deleted
  Employee a = (from b in edm.Employees
                where b.EmployeeID == txtboxForEmployeeId
                select B)/>.FirstOrDefault();



Not sure if this is best practice though. It works so im using it for now.
Was This Post Helpful? 0
  • +
  • -

#13 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Linq query result to int?

Posted 11 July 2012 - 07:08 AM

Well, a simple rewrite:

int id;
if(!int.TryParse(txtbxEmployeeId.Text, out id))
    //replace this with proper handling
    throw new Exception("Text was not numeric!"); 
var employee = edm.Employees.FirstOrDefault(b => b.EmployeeId = id);


It's safer with the try parse, and I believe that the LINQ is easier to understand when you have as few operations as possible. This just has one method.
Was This Post Helpful? 1
  • +
  • -

#14 gerdi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 11-July 12

Re: Linq query result to int?

Posted 13 July 2012 - 12:25 AM

Hey thanks. I think I get that linq , I can see where I will be able to use the TryParse in other areas of my code although I am not sure if I need to here. This is because the ID field is hidden and auto generates the increment int for the added user so there is now user input and so there should never be an error * I say never with all hope ;). Is this best practice to make it hidden? I figured it shouldn't be a problem but as I stated before I am a n00b and still getting my feet wet with c# and linq

View PostCurtis Rutland, on 11 July 2012 - 07:08 AM, said:

Well, a simple rewrite:

int id;
if(!int.TryParse(txtbxEmployeeId.Text, out id))
    //replace this with proper handling
    throw new Exception("Text was not numeric!"); 
var employee = edm.Employees.FirstOrDefault(b => b.EmployeeId = id);


It's safer with the try parse, and I believe that the LINQ is easier to understand when you have as few operations as possible. This just has one method.

Was This Post Helpful? 0
  • +
  • -

#15 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Linq query result to int?

Posted 13 July 2012 - 07:21 AM

Quote

This is because the ID field is hidden and auto generates the increment int for the added user


Is this for a database? Then no, this is bad practice. Databases have automatic ID columns that you should use rather than trying to generate unique keys yourself.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2