【发布时间】:2010-10-28 19:12:35
【问题描述】:
我一直在尝试使用更明智和精简的语法来清理以下方法,但是在使用 L2S 进行聚合子句和过滤时,我感到非常头疼。特别是,我觉得我应该能够使用 .Contains() 方法来过滤掉标签与方法中传递的字符串参数匹配的对象,但它没有奏效。
public TagListViewModel GetTagModel(string Name)
{
var model = new TagListViewModel();
var repo = new SimpleRepository("Wishlist");
var ideas = repo.All<Idea>();
List<Idea> ideaList = new List<Idea>();
foreach (Idea i in ideas)
{
var query = from tag in repo.All<Tag>()
join ideatag in repo.All<IdeaTag>()
on tag.ID equals ideatag.TagId
where ideatag.IdeaId == i.ID
select tag;
i.Tags = query.ToList<Tag>();
ideaList.Add(i);
}
foreach (Idea i in ideaList)
{
var query = from vote in repo.All<IdeaVotes>()
where vote.IdeaId == i.ID
select vote;
i.Votes = query.ToList<IdeaVotes>();
}
// Here begins the problem area. I should be able to get a tag from the repo
// whose name matches the "Name" parameter and then call a .Contains() method to
// filter this list, shouldn't I?
List<Idea> filteredTagList = new List<Idea>();
foreach (Idea item in ideaList){
foreach(Tag t in item.Tags)
{
if (t.Name == Name)
filteredTagList.Add(item);
}
}
model.Ideas = filteredTagList;
return model;
}
太丑了。我知道这很丑,但是在玩了几个首选的变体超过 2 小时后,我仍然无法让它按照它应该的方式过滤。我哪里错了?
【问题讨论】:
标签: c# linq-to-sql filtering