How to use Lambda in a LINQ select expression

I am trying to select stores using a lambda function and convert the result to SelectListItem so that I can display it. However, he throws " Type of expression in Select Clause is Incorrect ":

IEnumerable<SelectListItem> stores = from store in database.Stores where store.CompanyID == curCompany.ID select (s => new SelectListItem { Value = s.ID, Text = s.Name} ); ViewBag.storeSelector = stores; 

What am I doing wrong?

EDIT:

Also, how do I convert Int to String in this situation? The following does not work:

 select (s => new SelectListItem { Value = s.ID.ToString(), Text = s.Name} ); select (s => new SelectListItem { Value = s.ID + "", Text = s.Name} ); 

EDIT 2:

Output the conversion of Int to String. It is typical for Microsoft to forget to enable the int2string conversion function. Here is the actual workaround that everyone uses, with fully working syntax:

 select new SelectListItem { Value = SqlFunctions.StringConvert((double)store.ID), Text = store.Name }; 

To call this situation absurd is an understatement.

+42
c # lambda linq asp.net-mvc
Mar 22 '13 at 18:56
source share
3 answers

using LINQ query expression

  IEnumerable<SelectListItem> stores = from store in database.Stores where store.CompanyID == curCompany.ID select new SelectListItem { Value = store.Name, Text = store.ID }; ViewBag.storeSelector = stores; 

or using LINQ extension methods with lambda expressions

  IEnumerable<SelectListItem> stores = database.Stores .Where(store => store.CompanyID == curCompany.ID) .Select(store => new SelectListItem { Value = store.Name, Text = store.ID }); ViewBag.storeSelector = stores; 
+90
Mar 22 '13 at 18:58
source share

It seems you are trying to mix the syntax of the query expression and the "normal" lambda expression syntax. You can use:

 IEnumerable<SelectListItem> stores = from store in database.Stores where store.CompanyID == curCompany.ID select new SelectListItem { Value = store.Name, Text = store.ID}; ViewBag.storeSelector = stores; 

Or:

 IEnumerable<SelectListItem> stores = database.Stores .Where(store => store.CompanyID == curCompany.ID) .Select(s => new SelectListItem { Value = s.Name, Text = s.ID}); ViewBag.storeSelector = stores; 

You cannot mix these two as you try.

+14
Mar 22 '13 at 18:58
source share

Why not just use the whole lambda syntax?

 database.Stores.Where(s => s.CompanyID == curCompany.ID) .Select(s => new SelectListItem { Value = s.Name, Text = s.ID }); 
+14
Mar 22 '13 at 18:58
source share



All Articles