0

I have the folowing linq query.
How can I modify the query to return distinct values for CityFoo property only?

var query = from f in db.Foos
             join b in db.Bars on f.IDFoo equals b.IDFoo
             join fb in db.Fubars on b.IDBar equals fb.IDBar
             select new MyViewModel {
                    IDFoo = f.IDFoo,
                    NameFoo = f.NameFoo,
                    CityFoo = f.CityFoo,
                    NameBar = b.NameBar,
                    NameFubar = fb.NameFubar };
alex
  • 1,300
  • 1
  • 29
  • 64
  • What values are you expecting for the other properties? The first value for each CityFoo? – Joachim Isaksson Mar 19 '14 at 16:35
  • Yes, the first value for each CityFoo – alex Mar 19 '14 at 16:42
  • I think you need to add more detail as to what you actually require as implementing a `GROUP BY` or `DISTINCT` selection will each have their implications on your results (i.e. how do you want your results to change), You might find [this question](http://stackoverflow.com/questions/7325278/group-by-in-linq) useful regarding grouping (though you'd have to determine which aggregates are appropriate) or alternatively [this question](http://stackoverflow.com/questions/3519165/how-can-i-do-select-unique-with-linq) for selecting distinct records. – talegna Mar 19 '14 at 16:42

1 Answers1

0

I think you are missing information on your query. If you want the first value to be used on the other properties, you need to tell that to Linq

So I am guessing that you actually want to group and then take the first.

Or...something like this:

var query = from f in db.Foos
             join b in db.Bars on f.IDFoo equals b.IDFoo
             join fb in db.Fubars on b.IDBar equals fb.IDBar
             group  new { f, b, fb } by f.CityFoo into grp
             let first = grp.FirstOrDefault()
             select new MyViewModel {
                    IDFoo = first.f.IDFoo,
                    NameFoo = first.f.NameFoo,
                    CityFoo = grp.Key,
                    NameBar = first.b.NameBar,
                    NameFubar = first.fb.NameFubar };
Fabio Marreco
  • 2,186
  • 2
  • 23
  • 24