【发布时间】:2010-08-31 09:53:09
【问题描述】:
我目前在 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 能够轻松回答这个问题。
提前致谢!
【问题讨论】:
-
您已经解释了您将获得什么,但您希望获得什么?您是否希望生成的匿名类型的
tags属性是与博客关联的所有标签的字符串连接?
标签: c# linq linq-to-sql join