Linq-to-sql逻辑痛苦

时间:2010-10-28 11:02:55

标签: c# linq-to-sql filtering

我一直在尝试使用更合理和更精简的语法来清理以下方法,但是当涉及聚合子句和使用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;
}

这太丑了。我知道这很难看,但经过两个小时的玩几个首选变化,我仍然无法过滤它应该的方式。我哪里错了?

1 个答案:

答案 0 :(得分:2)

假设单个Idea上没有重复的标签,这应该是等效的。

model.Ideas = ideaList.Where(
                  idea => idea.Tags.Any(
                        tag => tag.Name == Name)).ToList();