无法转换类型'AnonymousType#1'

RPD*_*RPD 8 c# linq

你知道如何解决这个错误吗?它在这行"foreach(int in itemColl)"中显示错误

我该怎么办?

错误1无法将类型'AnonymousType#1'转换为'int'C:\ Users\Rafal\Desktop \MVCksią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);
                }
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 22

您正在itemColl使用new关键字选择,定义匿名类型,您不能应用类型foreach循环int.您当前的查询返回类似的内容IEnumerable<AnonymousType>

相反,你可以这样做:

var itemColl = from p in re.Kategorie
               where p.Nazwa == category
               select p.Id_Kat;
Run Code Online (Sandbox Code Playgroud)

这将返回IEnumerable<int>,您可以在当前的foreach循环中使用.

但是,如果要在匿名类型上选择使用当前查询,则必须使用隐式类型var修改foreach循环,并且由于当前查询返回匿名类型对象,因此可以Id_kat从对象中选择.就像是.

foreach (var s in itemColl)
{
    Console.WriteLine(s.Id_kat);
}
Run Code Online (Sandbox Code Playgroud)

IMO,不建议使用第二种方法,因为您只是返回一个int包含在匿名类型中的类型.如果您可以更改您的查询以返回它会更好IEnumerable<int>


Dav*_*haw 7

您只需将选择更改为:

var itemColl = from p in re.Kategorie 
    where p.Nazwa == category 
    select p.Id_kat;
Run Code Online (Sandbox Code Playgroud)

这将创建一个IEnumerable<int>你正在尝试使用的foreach.

select new { p.Id_Kat }是创建一个新的匿名类型这是在说,它是这样的一类新的简单的方法:

class AnonymousType#1
{
    public int Id_Kat {get; set;}
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*war 5

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);
               }
Run Code Online (Sandbox Code Playgroud)