【问题标题】:Type of one of the expressions in the join clause is incorrect连接子句中的表达式之一的类型不正确
【发布时间】:2014-04-14 02:33:42
【问题描述】:

我正在学习 LINQ 并尝试使用交叉连接我收到此错误:连接子句中的表达式之一的类型不正确

在 Cross Join 中不能使用 GetCategories() 吗?此请求在 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 } );

【问题讨论】:

  • 你的方法的返回类型是什么

标签: c# linq


【解决方案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 };

【讨论】:

  • 这有帮助吗?公共静态 IEnumerable GetProducts() 公共静态 IEnumerable GetCategories()
  • 我确实添加了更多行,以便您查看列表的情况
  • 获得 1 个错误,无法将类型 'string' 隐式转换为 'bool' 其中 c.Name = "Beverages" 无法弄清楚 bool 是如何进入其中的,无法在其中找到名称像这样的LINQ?
  • 感谢您的帮助,也许是最后的帮助,我正在尝试仅打印以 GI 开头的单词确实添加了行 orderby (p.name.Startswith("G"))但它会打印与 Beverages 具有相同 CategoryID 的每一行,而不仅仅是以 G 开头的单词。
  • 找到了,使用了 orderby,但改成了我得到的地方:)
猜你喜欢
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 2014-11-14
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多