Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select All distinct values in a column using LINQ

I created a Web Api in VS 2012. I am trying to get all the value from one column "Category", that is all the unique value, I don't want the list to be returned with duplicates.

I used this code to get products in a particular category. How do I get a full list of categories (All the unique values in the Category Column)?

public IEnumerable<Product> GetProductsByCategory(string category)
    {
        return repository.GetAllProducts().Where(
            p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
    }
like image 271
Tester Avatar asked Oct 23 '13 17:10

Tester


People also ask

How to select distinct in LINQ query?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

Why distinct is not working in LINQ?

LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.


3 Answers

To have unique Categories:

var uniqueCategories = repository.GetAllProducts()
                                 .Select(p => p.Category)
                                 .Distinct();
like image 147
Alireza Avatar answered Oct 04 '22 06:10

Alireza


var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

like image 31
Dmitry Gribkov Avatar answered Oct 02 '22 06:10

Dmitry Gribkov


I have to find distinct rows with the following details class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries

public DbSet<SCountry> country { get; set; }
    public List<SCountry> DoDistinct()
    {
        var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
        var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
        return Countries;
    }
like image 34
Basant tiwari Avatar answered Sep 30 '22 06:09

Basant tiwari