Unable to convert type to Anonymous Type # 1

Do you know how to fix this error? This line displays the error "foreach (int s in itemColl)"

What should I do?

Error 1: Cannot convert type โ€œAnonymous type # 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); } 
+6
source share
5 answers

You select itemColl with the keyword new , defining an anonymous type ; you cannot use a foreach with an int type. Your current query returns something like IEnumerable<AnonymousType>

Instead, you can:

 var itemColl = from p in re.Kategorie where p.Nazwa == category select p.Id_Kat; 

This will return an IEnumerable<int> and you can use it in the current foreach loop.

But if you want to use your current request with a choice of an anonymous type, you need to change your foreach loop with an implicit type of var , and since your current request is returning an object of an anonymous type, you can select Id_kat from the object. Sort of.

 foreach (var s in itemColl) { Console.WriteLine(s.Id_kat); } 

IMO, the second approach is not recommended because you simply return an int type wrapped in an anonymous type. Better if you can modify your request to return an IEnumerable<int>

+20
source

You just need to change the selection:

 var itemColl = from p in re.Kategorie where p.Nazwa == category select p.Id_kat; 

This will create the IEnumerable<int> that you are trying to use in foreach .

select new { p.Id_Kat } creates a new anonymous type , which in the simplest way says that it is a new class:

 class AnonymousType#1 { public int Id_Kat {get; set;} } 
+7
source
 var itemColl = from p in re.Kategorie where p.Nazwa == category //This is Anonymous Type select new { //Anonymous type attribute(s) go(es) here IntItem = p.Id_kat }; foreach (var s in itemColl) { Console.WriteLine(s.IntItem); } 
+5
source

Well, you can return a real (int) value instead of the anonymous linq result

 var itemColl = from p in re.Kategorie where p.Nazwa == category select p.Id_Kat; 
+4
source
 foreach (var s in itemColl) { Console.WriteLine(s.Id_kat); } 
-1
source

Source: https://habr.com/ru/post/922213/


All Articles