【问题标题】:Linq-to-sql logic painLinq-to-sql 逻辑痛
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 任何!这就是为什么它不起作用。我全神贯注于使用 Contains()。谢谢你。
    • 使用 Contains 只能匹配确切的元素,例如 tag,不能过滤 lambda 表达式。
    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多