c# - 无法从查询返回 linq 结果

标签 c# linq

嘿,我是 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();;
    }

最佳答案

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

select new
{
    Category = category,
    Item = item
}

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

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

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

关于c# - 无法从查询返回 linq 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668111/

相关文章:

c# - 如何在 C# 中的字节数组中查找字节模式?

.net - ListViewItemCollection 的字符串数组

c# - 将 IEnumerable 强制转换为 IList<TResult> 是否会枚举序列,为什么首选这种方式?

c# - 林奇 : Dynamic select

c# - 无论顺序如何,如何识别两个 List<string> 是否相等?

linq - 扩展方法转换为 LINQ 表达式和常用方法

c# - 将输出引用程序集构建到子文件夹

c# - 如何使用复合键选择器对 IEnumerable<T> 进行分组?

c# - 具有多个 Contains/Any 的 Linq

c# - 让我们加密 API 不返回根证书?