我目前有许多嵌套在foreach循环中的linq表达式......有点打败了使用linq的点!
我想要实现的是一个简单的博客模型(博客帖子有多个标签,并且与多个类别相关联......就是这样)。
我正在寻找一种方法将所有linq表达式压缩成单个表达式,而我此刻尝试这样做的方式并没有返回所需的结果。这是我目前正在尝试的基本表现:
var blogs =
from blog in db.BlogPosts
join categories in db.BlogCategories
on blog.Fk_Category_Id equals category.Id
// Using a junction table because blogs can have multiple tags,
// and tags can be shared across different blogs.
join juncTags in db.Junc_BlogTags
on blog.Id equals juncTags.Fk_BlogPost_Id
join tags in db.Tags
on juncTags.FK_Tag_Id equals tags.Id
select new
{
blog,
categories,
tags
};
foreach(var blog in blogs)
{
blog.blog // Correct, can obtain information of current blog...
blog.categories // Correct, shows the information of Blog's category
blog.tags // Wrong, only refers to the first tag - next itteration will
// show the same blog with the next tag .. not what I want.
}
我确信这里有一些简单的东西,我在这里找不到,但无法理解,并认为Stack Overflow能够轻松解决这个问题。
提前致谢!
答案 0 :(得分:1)
目前尚不清楚你最想要的是什么,而不是你现在得到的,但是这个怎么样?
var blogs = from blog in db.BlogPosts
join categories in db.BlogCategories
on blog.Fk_Category_Id equals category.Id
select new
{
blog,
categories,
tags = from juncTags in db.Junc_BlogTags
join tags in db.Tags
on juncTags.FK_Tag_Id equals tags.Id
where juncTags.Fk_BlogPost_Id = blog.Id
select tags
};