0

asp.net mvc 4, Entity Framework 5, SQL Server 2012 Express, Code First

I have a Place model:

public virtual int PlaceID { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual string Name { get; set; }

and a related Tag model:

public virtual int TagID { get; set; }
public virtual string Name { get; set; }
public virtual string NamePlural { get; set; }
public virtual ICollection<Place> Places { get; set; }

they have a many to many relationship.

I have a List places - and I would like to create a List tags - populated with every (unique) tag associated with every place in 'places'.

For example, one place might have 'restaurant' and 'pub' tag, another 'pub' and 'bar', and another 'shop' and 'cafe'.

I would like the List to contain one of each of the tags with these names: Bar, Cafe, Restaurant, Pub, Shop

How can I do this in Linq?

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
niico
  • 11,206
  • 23
  • 78
  • 161

1 Answers1

0

If you want all the unique tag names you can do:

places.SelectMany(x => x.Tags).Select(x => x.Name).Distinct()

if the two instances of the same tag are the same object then you can just do

places.SelectMany(x => x.Tags).Distinct();

if they are different objects then you can do

places.SelectMany(x => x.Tags).GroupBy(x => x.TagId).Select(g => g.First());

UPDATE after new comment.

Add ToList() to then end to convert the result into a list.

places.SelectMany(x => x.Tags).Select(x => x.Name).Distinct().ToList();
places.SelectMany(x => x.Tags).Distinct().ToList();
places.SelectMany(x => x.Tags).GroupBy(x => x.TagId).Select(g => g.First()).ToList();
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • Thanks - getting this error: The model item passed into the dictionary is of type 'System.Linq.Enumerable+d__81`1[myapp.Models.Tag]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[myapp.Models.Tag]'. – niico Jun 07 '13 at 15:10