2016-09-23 52 views
1

嘿所以我对C#比较陌生,因为我在开始这项工作之前从未使用它。我试图从linq查询中返回结果集。然而,我遇到的问题是它的类型是匿名的。我曾尝试创建一个自定义类型,所以我可以使用它,但我仍然得到一个错误信息:无法从查询中返回linq结果

Severity Code Description Project File Line Suppression State 
Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable<<anonymous type: 
SCSEntities.SCS_ItemCategory Category, SCSEntities.SCS_Item Item>>' to 
'System.Collections.Generic.List<SchoolCash.DataFactory.ItemFactory.ExportItemTable>'. 
An explicit conversion exists (are you missing a cast?) SchoolCash.DataFactory 
C:\seamysCode\SCA\4.12\Common\SchoolCash.DataFactory\ItemFactory.cs 551 Active 

所以我想知道我失去了一些东西在这里,因为我已经看过了的东西说来创造根据需要使用get和setter的自定义类型。然后,我应该能够返回它。我想知道是否有人可以帮助我,因为从我有限的眼睛可以看到我正确地做到了这一点。我很感激提前的帮助。

public class ExportItemTable 
    { 
     public SCS_ItemCategory Category { get; set; } 
     public Item Item { get; set; } 
    } 

    public List<ExportItemTable> GetItemExportTable() 
    { 

     var result = 

     from item in Context.SCS_Items 
     join category in Context.SCS_ItemCategories 
     on item.ItemPk equals category.ItemFk 
     into temp 
     from category in temp.DefaultIfEmpty() 

     select new 
     { 
     Category = category, 
     Item = item 
     }; 

     return result.ToList();; 
    } 
+1

错误是告诉你问题是什么..你应该查询返回,预计其类型是一个列表所以你只需要使用Linq中提供给您的扩展方法,并使用'.ToList( )'如果类型返回需要一个数组..然后相同的'.ToArray()'有大量的免费教程以及MSDN,你可以下载大量的教程,它们的源代码可以在那里玩耍和学习与此同时 – MethodMan

回答

4

此代码创建一个匿名类型:

select new 
{ 
    Category = category, 
    Item = item 
} 

你只需要像这样创建所需类型的实例:

select new ExportItemTable() 
{ 
    Category = category, 
    Item = item 
} 

在一些语言(如打字稿)如果你有一个与预期类型的​​属性相匹配的对象,编译器会将它们视为同一事物。 C#不会这样做,并强制您显式创建要使用的类型的实例。

0

修改如下:

select new ExportItemTable 
      { 
      Category = category, 
      Item = item 
      }; 

return result.AsEnumerable().ToList() 

详情:

  • 您需要ExportItemTable的结果,所以不能用Anonymous type,假设Category and Item有映射类型
  • 现在你IQueryable<ExportItemTable> ,但您需要返回List<ExportItemTable>,因此请转换为