c# LINQ: how to retrieve a single result

后端 未结 8 1395
梦如初夏
梦如初夏 2020-12-29 07:00

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.productIn         


        
相关标签:
8条回答
  • 2020-12-29 07:23

    By using First() or FirstOrDefault()

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

    Only use Single() or SingleOrDefault() if you know there is only one result, or if you want to fail if there are multiple results.

    0 讨论(0)
  • 2020-12-29 07:28

    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();
    
    0 讨论(0)
提交回复
热议问题