Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am getting an issue while implementing this code:

C#
public static List<SubCategoryInfo> GetPageByCategorySEOName(string PageName, string SubPageName)
   {
       return (from p in GetAllPageByCategorySEOName()
               where (p.CategorySEOName.Equals(PageName, StringComparison.OrdinalIgnoreCase) ||
                      p.SubCategorySEOName.Equals(SubPageName, StringComparison.OrdinalIgnoreCase))
                     && (p.CategorySEOName.Equals(PageName, StringComparison.OrdinalIgnoreCase) ||
                     p.SubCategorySEOName.Equals(SubPageName, StringComparison.OrdinalIgnoreCase))
                     select p).Distinct().ToList();
   }


The idea come from this sql query which work as expected:

SQL
select distinct  c.CategorySEOName from [dbo].[SubCategory] Sc
     inner join [dbo].[Category] C on C.CategoryId = Sc.CategoryId
     where (c.categorySEOName in('aboutus') or Sc.SubcategorySEOName in('""'))
     and ( c.categorySEOName in('aboutus') or Sc.SubcategorySEOName in('Our-values'))


the sql query work fine with distinct but not for the linq c# code.

Please can anyone help telling me why the distinct of the linq c# code do not work, in my case it duplicates data is why I want to use distinct as for the sql query which work fine.
Posted
Updated 2-Mar-18 7:56am

Try GroupBy and than do the select... For example ...

XML
List<Person> distinctPeople = allPeople
  .GroupBy(p => p.PersonId)
  .Select(g => g.First())
  .ToList();
 
Share this answer
 
Comments
Maciej Los 24-Mar-14 18:43pm    
+5
Member 13767903 7-Apr-18 23:37pm    
good .it's working.
With DISTINCT I suppose that you want to remove duplicates.
But you are doing the DISTINCT on object level in the Linq code, i.e on object p.
objects are compared by their GetHashCode value

In the sql you are doing Distinct on p.CategorySEOName

What you need is a Distinct that take an expression
But that doesn't exist :)

You can possibly use group by instead.

myList.GroupBy(p => p.CategorySEOName).Select(g => g.First())
 
Share this answer
 
Comments
Matt T Heffron 24-Mar-14 18:28pm    
But it can take an IEqualityComparer<T> so a simple EqualityComparer class could be implemented that compared the p.CategorySEOName for .Equals and used that for computing .GetHashCode() see http://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx
Mattias Högström 25-Mar-14 5:02am    
I haven't worked with Linq for a couple of years.
I remember vaguely that I used an extension method back in the days for this to work-around it.
Good finding.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900