none
can I use a lambda expression in this Linq Select query? RRS feed

  • Question

  • Here is the model for the Linq Query -- is there a way I could rewrite the following Linq query using  a   => Lambda Expresseion?

    public class ProductModel
    {
       public string ProductName { get; set; }
       public int MobileSalesCount { get; set; }
    }

    Here is the Linq Query

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString()))
    {
       var productdata = con.Query<ProductModel>("Usp_GetTotalsalesProductwise", null, null, true, 0, CommandType.StoredProcedure).ToList();
    
       var MobileSalesCounts = (from temp in productdata
                                      select temp.MobileSalesCount).ToList();
    }

    Here is the list that Usp_GetTotalsalesProductwise returns

    ProductName MobileSalesCount
    'Apple' 43
    'Honor' 9
    'Ml' 12
    'Motorola' 28
    'Samsung' 21

    How could I rewrite the Linq Query above using =>  to return the same list?  or actually just return the list of MobileSalesCount?


    Rich P

    Tuesday, September 26, 2017 7:27 PM

Answers

  • How about this?:
    var MobileSalesCounts = productdata.Select(temp => temp.MobileSalesCount).ToList();


    TEHIII

    • Marked as answer by Rich P123 Tuesday, September 26, 2017 8:10 PM
    Tuesday, September 26, 2017 8:04 PM

All replies

  • How about this?:
    var MobileSalesCounts = productdata.Select(temp => temp.MobileSalesCount).ToList();


    TEHIII

    • Marked as answer by Rich P123 Tuesday, September 26, 2017 8:10 PM
    Tuesday, September 26, 2017 8:04 PM
  • Also, try something like this:
    List<string> lst_strReport = productdata.Select(temp => string.Format("{0}\t{1}", temp.ProductName, temp.MobileSalesCount)).ToList();


    TEHIII

    Tuesday, September 26, 2017 8:07 PM
  • var MobileSalesCounts = productdata.Select(temp => temp.MobileSalesCount).ToList();

    Thank you.  This does return the same values as the non =>.



    Rich P

    Tuesday, September 26, 2017 8:11 PM