I am trying to select stores using a lambda function and converting the result to a SelectListItem so I can render it. However it is throwing a "Type of Expression in Select Clause is Incorrect" error:
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:
Figure out the Int to String conversion. It is so typical of Microsoft to forget to include an int2string conversion function. Here is the actual workaround everyone is using, with fully working syntax:
select new SelectListItem { Value = SqlFunctions.StringConvert((double)store.ID), Text = store.Name };
To call this situation absurd is an understatement.
select (s => new SelectListItem { Value = s. ID. ToString(), Text = s.Name} ); select (s => new SelectListItem { Value = s.ID + "", Text = s.Name} );
Advertisements. The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.
The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.
So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.
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;
Why not just use all Lambda syntax?
database.Stores.Where(s => s.CompanyID == curCompany.ID) .Select(s => new SelectListItem { Value = s.Name, Text = s.ID });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With