c# - join 子句中的表达式之一的类型不正确

标签 c# linq

我正在学习 LINQ 并尝试使用交叉联接,但出现此错误:联接子句中的表达式之一的类型不正确

不能在交叉连接中使用 GetCategories() 吗?该请求位于 main 中,但函数位于 main 之外。

var q = from c in GetCategories()
        join p in GetProducts() on c equals p.CategoryID
        where c.Name = "Beverages"
        select new { ID = c, p.Name };

方法签名:

public static IEnumerable<Category> GetCategories()
List<Category> categories = new List<Category>( );
categories.Add( new Category { ID = 1, Name = "Beverages" } );

public static IEnumerable<Product> GetProducts()
List<Product> products = new List<Product>( );
products.Add( new Product { Name = "Milk",           Price = 90,  CategoryID = 4, ID = 1 } );

最佳答案

您需要指定要加入 Category 类中的哪个字段。最有可能的是 ID:

from c in GetCategories()
join p in GetProducts() on c.ID equals p.CategoryID
where c.Name == "Beverages"
select new { ID = c.ID, p.Name };

关于c# - join 子句中的表达式之一的类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22309493/

相关文章:

c# - 禁用 DataTable 更改跟踪

c# - Jwt 代码不适用于 .NET Core 2

C# 泛型接口(interface)协变

linq - 如何拒绝 Linq to SQL DataContext 中的所有更改?

c# - 我如何在 C# 中编写这样的代码生成类?

c# - 通用谓词的默认值作为参数

c# - 我如何从数组和列表中创建带有键的字典?

c# - 不带组的对象的 Linq 总和

java - scala -> 在同一程序中使用 .net (linq) 和 java 代码库?

c# - 使用联接时跟踪 LINQ