我正在学习 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/