Reputation: 494
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);
}
Upvotes: 8
Views: 28211
Reputation: 223412
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>
Upvotes: 25
Reputation: 2569
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);
}
Upvotes: 5
Reputation: 52818
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;}
}
Upvotes: 7
Reputation: 5895
Well, you could return a real (int)-value instead of an anonymous linq-result
var itemColl = from p in re.Kategorie
where p.Nazwa == category
select p.Id_Kat;
Upvotes: 4