【发布时间】:2011-04-06 04:57:46
【问题描述】:
我总是发现自己在创建仍然大量使用嵌套 foreach 循环的 linq 表达式。下面是我所说的一个简单示例,如果这里有人能告诉我如何将这种低效率的代码压缩成单个 linq 表达式,我将非常感激?
数据库上下文(db)有三个表:Blog、Tag、Junc_Tag_Blog。联结表只是存储带有标签的博客记录。
不管怎样,这是我乱七八糟的代码:
public static Collection<Blog> GetByTag(string tagName)
{
// Get the tag record.
var tag = (from t in db.Tags
where t.Name == tagName
select t).Single();
// Get the list of all junction table records.
var tagJunc = from tj in db.Junc_Tag_Blogs
where tj.Fk_Tag_Id == tag.Id
select tj;
// Get a list of all blogs.
var blogs = from b in db.BlogPosts
select b;
// Work out if each blog is associated with given tag.
foreach(var blog in blogs)
{
foreach(var junc in tagJunc)
{
if(blog.Id == junc.Fk_Blog_Id)
{
// We have a match! - do something with this result.
}
}
}
}
提前感谢能帮我清理这段代码的人!
【问题讨论】:
标签: c# linq linq-to-sql optimization foreach