0

I need to select all Places with a particular tag then iterate over them:

public class Place {
    public int Id { get; set; }
    public string PlaceName { get; set; }

    public IEnumerable<Tag> Tags { get; set; }
}

public class Tag {
    public int Id { get; set; }
    public string TagName { get; set; }
}

Each place can have multiple tags. Each tag can belong to multiple places.

In Linq - I need to select all Places that have a particular tag - eg this tag:

var Bar = new Tag {
    Id = 1,
    TagName = "Bar"
}

I've tried this:

foreach (var Bar in Model.Places.Where(x => x.Tags.Contains(Bar)))

But the foreach never gets iterated over - the Contains returns nothing (and many of the Places do have a Bar object in their collection of Tags)

I found this - it appears to say my approach should work?

Linq to Select Parent Objects Where Child Objects Have a Matching Child Object

Should this work / am I missing something? Is there a better way to do it?

Thanks.

Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
niico
  • 11,206
  • 23
  • 78
  • 161
  • 1
    Your example is too minimalized. It looks like you are comparing two different Bar objects though, one created and one exists. The problem is that the created one will be different than the existing one as object comparison is done based on memory location. – Travis J Jun 11 '18 at 21:43
  • It would be awesome if you could provide a [mcve] (with sample inputs and expected results) that we could copy and paste into a console app. – mjwills Jun 11 '18 at 21:43
  • 1
    `foreach (var Bar in Model.Places.Where(x => x.Tags.Any(b => b.Id == 1 && b.TagName == "Bar")))` – Ousmane D. Jun 11 '18 at 21:44
  • @Aominè Thanks (slight typo should be == 1) - but thanks that & Travis gave me what I need. – niico Jun 11 '18 at 21:47

0 Answers0