Andy Jones
Andy Jones

Reputation: 869

Linq - Select list of tags from a list objects, each containing a list of tags

I'm a little bit stumped with this Linq statement. My basic database structure is:

* Event (ID, Name, VenueID)
* Venue (ID, Name)
* EventTag (EventID, TagID)
* VenueTag (VenueID, TagID)
* Tag (TagID, Name)

I get a list of events, each event has a list of EventTags (which has a list of tags), and each event has a venue, which has a list of venue tags, which has a list of tags.

What I am trying to get is a distinct list of tags that are used between all the events.

I have tried a few things, but I either get a list of EventTags, and VenueTags, which may or may not hold tags, or nothing...

Some of my attempts have been (and I may be way off, so don't laugh!):

 var tags = events.Select(x=>x.EventTag.Select(x=>x.Tag)).Union(events.Select(y=>y.Venue.VenueTag.Select(z=>z.Tag))).Distrinct().ToList()

Or

var tags1 = (from y in (from x in events where events.EventTags.Count > 0 select x) select y.Tag).ToList

I was then hoping to do the same with Venue and put them together, but no luck...

Thanks in advance!

Upvotes: 1

Views: 505

Answers (2)

Joe
Joe

Reputation: 2601

First solution that came to my mind, maybe it's not the best one.

1- get the list of all tags as Distinct list. var tags = Tag.Distinct().ToList();

2- var comonTags = tags.ForEach(tag => CheckIfComon(tag) );

3- create a method CheckIfComon(tags), and check if the tag exists in all events and venue. you can do that by foreach event and return in contains tag, then check the number of return event if the same as the count of all events.

Regards

Upvotes: 0

Andrei
Andrei

Reputation: 56716

You were very close first time - just needed SelectMany instead of Select to get all tags for each entity:

events.SelectMany(x => x.EventTag).Select(et => et.Tag)
      .Union(events.SelectMany(x => x.Venue.VenueTag).Select(vt => vt.Tag))
      .Distrinct().ToList();

Upvotes: 1

Related Questions