Search code examples
c#linqscalar

c# LINQ: how to retrieve a single result


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;

Solution

  • 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;