Building a Linq Query gives me a question.

So here I am building a new site that will estimate around 500,000 page views and 50,000 database transactions DAILY.  I am currently working on a simple query that selects ONE row[column] from a database and returns the value to the rest of the methods.  I have a simple thought or question I would like answered and thought this would be a place to bring it up.

Is the foreach loop required even if I know I will receive only 1 record back from the database?

That's it and to give you an example:

        CS_Code.DataContext db = new CS_Code.DataContext(SQLStatementsCS.ConnectionStringID());
        var query = from RN in db.Province
                    where RN.Name == Name
                    select RN.uid;

        int value;
        foreach (var uid in query)
        { value = uid; }


I think it is kind of pointless to create a foreach loop and use 3 lines of code to just get an ID out of the database. So let me know in the comments section if this is the only answer and I will point out the answer and give you a link back to a site of your choice.

Thanks guys and dolls.

kick it on DotNetKicks.com

DZone It!
DZone
StumbleUpon
StumbleUpon
Digg It!
Digg It!



Related posts

Comments

Posted on April 7. 2008 11:33 AM

VidalSasoon

VidalSasoon ca
Maybe you need "Take"?


weblogs.asp.net/.../...NET-_2800_Part-1_2900_.aspx
====================
TravelOrganizer travel = new TravelOrganizer();

GridView1.DataSource = (from location in travel.PlacesVisited
orderby location.Distance descending
select location).Skip(1).Take(5);
GridView1.DataBind();

Posted on April 7. 2008 11:41 AM

Scott

Scott us
The problem with that, is I am not using a Girdview and only returning one row and one row only. So what you just gave me won't help. Sorry.

Posted on April 7. 2008 01:24 PM

Michael Reyeros

Michael Reyeros us
You could try using the Single Linq operator:
db.Provinces.Single(p => p.Name == Name);

Posted on April 7. 2008 03:01 PM

justin

justin us
int value = (from RN in db.Province
where RN.Name == Name
select RN.uid).FirstOrDefault();

Posted on April 19. 2008 01:19 PM

Scott

Scott us
Thanks Justin. That works. I appreciate the help guys.

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]







Sign in