Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert type 'AnonymousType#1'

Tags:

c#

linq

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);
                }
like image 341
RPD Avatar asked Aug 06 '12 12:08

RPD


3 Answers

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>

like image 122
Habib Avatar answered Oct 05 '22 12:10

Habib


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;}
}
like image 42
DaveShaw Avatar answered Oct 05 '22 11:10

DaveShaw


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);
               }
like image 29
Pravin Pawar Avatar answered Oct 05 '22 11:10

Pravin Pawar