【问题标题】:Cannot return linq result from query无法从查询返回 linq 结果
【发布时间】:2016-09-23 19:19:17
【问题描述】:

嘿,所以我对C# 还很陌生,因为在开始这项工作之前我从未使用过它。我正在尝试从 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();;
    }

【问题讨论】:

  • 错误告诉你问题是什么......你应该将查询返回到它期望的类型,即 List 所以你只需使用 Linq 中提供给你的扩展方法和如果类型返回需要一个数组,请使用.ToList() ..那么相同的.ToArray() 有大量免费教程以及 MSDN,您可以下载大量包含源代码的教程,您可以在其中玩耍和学习同时

标签: c# linq


【解决方案1】:

这段代码创建了一个匿名类型:

select new
{
    Category = category,
    Item = item
}

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

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

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

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 2010-09-25
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多