Do you know how fix this error? It` s show error in this line "foreach (int s in itemColl)"
What I have to do?
Error 1 Cannot convert type 'AnonymousType#1' to 'int' C:\Users\Rafal\Desktop\MVC ksiązka\moj projekt\sklep\SportsStore.WebUI\Controllers\ProductController.cs 37 21 SportsStore.WebUI
var itemColl = from p in re.Kategorie
where p.Nazwa == category
select new
{
p.Id_kat
};
foreach (int s in itemColl)
{
Console.WriteLine(s);
}
You are selecting itemColl
with new
keyword, defining an anonymous type, you can't apply foreach
loop with int
type. Your current query is returning something like IEnumerable<AnonymousType>
Instead you may do:
var itemColl = from p in re.Kategorie
where p.Nazwa == category
select p.Id_Kat;
This will return IEnumerable<int>
and that you can use in your current foreach loop.
But if you want to use your current query with selection on anonymous type, you have to modify your foreach loop with implicit type var, and since your current query is returning an anonymous type object you may select the Id_kat
from the object. Something like.
foreach (var s in itemColl)
{
Console.WriteLine(s.Id_kat);
}
IMO, the second approach is not recommended because you are just returning an int
type wrapped inside an anonymous type. Its better if you can change your query to return IEnumerable<int>
You just need to change the select to:
var itemColl = from p in re.Kategorie
where p.Nazwa == category
select p.Id_kat;
This will create an IEnumerable<int>
which is what you are trying to use in the foreach
.
The select new { p.Id_Kat }
is creating a new Anonymous Type which is in the simplest way of saying it is a new class like this:
class AnonymousType#1
{
public int Id_Kat {get; set;}
}
var itemColl = from p in re.Kategorie
where p.Nazwa == category
//This is Anonymous Type
select new
{
//Anonymous type's attribute(s) go(es) here
IntItem = p.Id_kat
};
foreach (var s in itemColl)
{
Console.WriteLine(s.IntItem);
}
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