Batsu
Batsu

Reputation: 55

Linq, unable to list only distinct results

I have three tables, car_type, car_manufacturer and car_model. When the user click on the particular vehicle type they want to browse, I'd like to show them a list of available manufacturers. The problem is the list of manufacturers is not distinct or unique. So if my db has three models from Mazda, Mazda will show up on the list 3 times. This is my controller:

    public ActionResult Browse(string click_string)     
    {
         var x = carDB.Models
                 .Include(b => b.Manufacturer)
                 .Include(a => a.VehicleType)
                 .Where(a => a.VehicleType.TypeName == click_string);
         return View(x.ToList());
}

How can I write this to remove redundant listings? This is all new to me, so go easy on me.

Upvotes: 0

Views: 233

Answers (5)

Kenneth Garza
Kenneth Garza

Reputation: 1916

add distinct

var x = carDB.Models
        .Include(b => b.Manufacturer)
        .Include(a => a.VehicleType)
        .Where(a => a.VehicleType.TypeName == click_string)
        .Select(y => y)
        .Distinct();

The .Select() might be a bit verbose but without trying it in my visual studio i put it in there for saftey

Upvotes: 0

Jason Berkan
Jason Berkan

Reputation: 8884

You should be able to use .Distinct to return the distinct elements.

var x = carDB.Models
        .Include(b => b.Manufacturer)
        .Include(a => a.VehicleType)
        .Where(a => a.VehicleType.TypeName == click_string)
        .Distinct();

Upvotes: 0

Gert Arnold
Gert Arnold

Reputation: 109119

It usually works well to try and avoid Distinct altogether. You want manufacturers? Get manufacturers. And determine from there which ones you need: the ones that produce models that have click_string in their type name:

carDB.Manufacturers.Where(manufacturer => manufacturer.Models
                   .Any(model => model.VehicleType.TypeName == click_string))

You may want to include Models and/or VehicleType, that depends on what you want to show in the view.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You have to query for Manufacturers, not for Vehicles:

var x = carDB.Models.Where(a => a.VehicleType.TypeName == click_string)
                    .Select(a => a.Manufacturer)
                    .Distinct();

Upvotes: 1

AD.Net
AD.Net

Reputation: 13399

First try doing a .Distinct() at the end of the query, if it does not work you might need to provide a custom comparer for the .Distinct()

Upvotes: 0

Related Questions