tags:

views:

357

answers:

3

I am trying to get a distinct list of tags for a record. It sort of works except the tag name is always the first one repeated.

public EntityCollection<TagEntity> Tags
    {
        get
        {
            EntityCollection<TagEntity> x = new EntityCollection<TagEntity>()
           {
                new TagEntity(){Id=1, IsActive=true, Name="Tag1"},
                new TagEntity(){Id=2, IsActive=true, Name="Tag2"},
                new TagEntity(){Id=3, IsActive=true, Name="Tag3"},
                new TagEntity(){Id=4, IsActive=true, Name="Tag1"},
                new TagEntity(){Id=5, IsActive=true, Name="Tag5"},
                new TagEntity(){Id=6, IsActive=true, Name="Tag6"},
            };

            return x;
        }
    }

    public EntityCollection<StoryTagsEntity> StoryTags
    {
        get
        {
            EntityCollection<StoryTagsEntity> x = new EntityCollection<StoryTagsEntity>()
           {
                new StoryTagsEntity(){ TagId=1, StoryId=1},
                new StoryTagsEntity(){ TagId=1, StoryId=2},
                new StoryTagsEntity(){ TagId=2, StoryId=1},
                new StoryTagsEntity(){ TagId=3, StoryId=1},
                new StoryTagsEntity(){ TagId=2, StoryId=3},
                new StoryTagsEntity(){ TagId=4, StoryId=1},
            };

            return x;
        }
    }

    public List<string> FetchTagNamesByStory(bool? isActive, int StoryId)
    {
        var d = (from t in this.Tags
                 join st in this.StoryTags on t.Id equals st.StoryId
                 where t.IsActive == isActive.GetValueOrDefault() && st.StoryId == StoryId
                 select t.Name);

        List<string> x = new List<string>();

        foreach (var item in d)
        {
            x.Add(item);
        }

        return x;
    }

Which results in a list of tags like this:

Tag1, Tag1, Tag1, Tag1

Where that should be:

Tag 1, Tag2, Tag3, Tag1

Any ideas?

A: 

My stupidity for all the internet to see!

The join was wrong, I was joining the wrong fields.

William
A: 

You're joining t.Id to st.StoryId instead of st.TagId. If you pass in StoryId of 1, you'll always get Tag1.

dahlbyk
A: 

You are correct, your join was wrong, also you can do the following:

public List<string> FetchTagNamesByStory(bool? isActive, int storyId)
{
    return (from t in Tags
        join st in StoryTags on t.Id equals st.TagId
        where t.IsActive == isActive.GetValueOrDefault() && st.StoryId == storyId
        select t.Name).ToList();
}
Yuriy Faktorovich