Convert IQueryable <int> to <int>
I want to select the price level in the database for comparison with an integer. But this is a mistake: the operator '==' cannot be applied to operands like "System.Linq.IQueryable" and "int". This is my code:
if (Request.IsAuthenticated){ CustomerModels cm = new CustomerModels(); string userName = Page.User.Identity.Name; var list_pricelevel = from c in cm.DataContext.Customers where c.WebAccount == userName select c.PriceLevel; if (list_pricelevel == 3) { Response.Write("Welcome"); } } var list_pricelevel
This definition is not int , because more than one row can be returned.
I don't use SQL syntax (lambda only), but in the end you need the equivalent of .FirstOrDefault or Single or First . We mainly accept the first row.
replace:
if (list_pricelevel == 3) from:
if (list_pricelevel.First() == 3) as you can see here: http://msdn.microsoft.com/en-us/library/bb291976.aspx if you are sure that there is a result or use FirstOrDefault ...
when you have the result of a LinQ expression, you will always have a list of results.
So, in your code, when you request, as shown below:
var list_pricelevel = from c in cm.DataContext.Customers where c.WebAccount == userName select c.PriceLevel;
List_pricelevel will be in the form of a List, i.e. IQueryable list
so you only need to get one item to check with one item
use the code below:
if (list_pricelevel.Single() == 3) { Response.Write("Welcome"); } or if (list_pricelevel.First() == 3) { Response.Write("Welcome"); } both the above code gives you only one result set value so you can equate with 3 for validation. Here is my suggestion:
if (list_pricelevel.First() == 3) { Response.Write("Welcome"); } This can lead to a NullReferenceException if there is no element in Clients that matches where c.WebAccount == userName .
Explanation:
list_pricelevel are IEnumerable elements matching your where clause.
You need to get the first item from your collection.
if (list_pricelevel.First() == 3) { Response.Write("Welcome"); } What is the beauty of Linq, that every query returns IQueryable so that you can defer getting the final result until you decide what you want. In another word, you can execute the query for another query :) Therefore, in order to get real data from the query, you must execute a command on it, which actually returns what you want. In your case, since you expect your query to return only one value, any methods like "FirstOrDefault", "Single" or "First" will do the trick