c# LINQ: how to retrieve a single result

后端 未结 8 1393
梦如初夏
梦如初夏 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:17

    use SingleOrDefault() if your query always returns only one element as result or exception will be thrown if the result of your query is more than one element.

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

    use FirstOrDefualt() if your result more than one element and you need any one of then.

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

提交回复
热议问题