locked
how can i get object from iqueryable RRS feed

  • Question

  • User-1232255770 posted

    var mp = Products.Where(mpn => mpn.ProductName == App).Take(1);

    returns

    iqueryable<Product>;

    How can i get the product returned  , without using a for each loop ?

    for example  :  Product p =  ?? ;

    Monday, March 19, 2018 11:21 AM

Answers

  • User753101303 posted

    Hi, depending on what the query is expected to return you could use First, FirstOrDefault, Single or SingleOrDefault. For example if you expect your query to return always 1 row :

    var mp = Products.Single(mpn => mpn.ProductName == App);

    And it will throw if the query doesn't return exactly one row.

    • if you expect 0 to n rows, use FirstOrDefault
    • if you expect 1 to n rows, use First
    • if you expect 1 row, use Single
    • if you expect 0 or 1 row, use SingleOrDefault

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 19, 2018 11:55 AM