Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# LINQ: how to retrieve a single result

Tags:

Kind of new to linq,

whats the simplest way to retrieve a single result using linq?

example, my query

var query =
     from c in db.productInfo
     where c.flavor == "Classic Coke" && c.container == "Can"
     select c.co2Target;

it should only return a single field with a double value. how do i pull it out of query? In the past i had used ExecuteScalar. How do i do it with linq? I would like to preserve its data type

UPDATE:

Here's where I am now. The problem is that the test query im running here is returning 4 instead of 3.75

var query =
                (from a in db.LUT_ProductInfos
                 where a.flavor == "Classic Coke" && a.Container == "Can"
                 select new { a.co2High }).Single();

            double MyVar = query.co2High.Value;
like image 260
Sinaesthetic Avatar asked May 16 '11 09:05

Sinaesthetic


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.


2 Answers

I think you mean return one value, not one record? You would need to do select new {} as follows:

var query =
     from c in db.productInfo
     where c.flavor == "Classic Coke" && c.container == "Can"
     select new { c.co2Target };

Then if you only want to retrieve a single record as well as that:

var query =
     (from c in db.productInfo
     where c.flavor == "Classic Coke" && c.container == "Can"
     select new { c.co2Target }).Single();

Retrieval would be done as follows:

var query =
         (from c in db.productInfo
         where c.flavor == "Classic Coke" && c.container == "Can"
         select new { c.co2Target }).Single();

double MyVar = query.co2Target;
like image 69
Tom Gullen Avatar answered Sep 19 '22 13:09

Tom Gullen


Use the .Single() or .SingleOrDefault() extension methods.

var query =
     (from c in db.productInfo
     where c.flavor == "Classic Coke" && c.container == "Can"
     select c.co2Target).Single();
like image 21
BenCr Avatar answered Sep 20 '22 13:09

BenCr