我是 c# 的新手,我正在学习...
我有两个表,Blog 和 BlogCategories。 Blog 表有一个引用 BlogCategories 中类别的 ID。
我对连接的语法有疑问:
var categories = new List<BlogCategory>();
if (model.BlogCategoryId.HasValue)
{
var query =
from category in categories
join blog in model on category.Id equals model.BlogCategoryId
select new { BlogCategory = category.Name };
}
问题是它不喜欢连接和获取:
Error CS1941 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'
任何帮助将不胜感激...PHP 不是一门大男孩语言,这是。
快速表结构 博客帖子表: ID, 博客类别, 标题, 内容
博客类别: ID, 类别名称
编辑: 解决方案似乎可行,但在某处出错:
var blogPosts = PopulateBlogPosts();
if (model.BlogCategoryId.HasValue)
{
var blogPostCategories = PopulateBlogCategories();
blogPosts = blogPostCategories.Where(c => c.Id == model.BlogCategoryId).Single();
}
最佳答案
假设categories
是一个 IEnumerable<BlogCategory>
.
var category = categories.Single(c => c.Id == model.BlogCategoryId);
这 Single
扩展方法断言您只希望匹配一个对象,并且它允许您进行过滤。如果满足过滤条件的不是一个类别,它将抛出异常。这是一个较短的形式:
var category = categories.Where(c => c.Id == model.BlogCategoryId).Single();
关于c# - C# 中的 Linq 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35097082/