Click here to Skip to main content
15,910,009 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of type `Myclass`
C#
List<Myclass> liSubjectIdDetail = new List<Myclass>();


where Myclass looks like
C#
public class  Myclass
  {
      public Nullable<decimal> SubjectId { get; set; }
      public string SubjectName { get; set; }
  }

I am adding records into liSubjectIdDetail from a table

C#
foreach (decimal Id in VarCEMSIdDetail)
  {
      liSubjectIdDetail.AddRange(db.Stt.MyTable.Where(x => x.Id == Id).Select(x => new Myclass { SubjectId = x.SubjectId, SubjectName = x.SubjectName }).ToList());
  }


where Id contains a list of certain Ids on the basis of which records I fetch.

Now I want to get only distinct records in this list.

I have tried it with hashtable in place of List
and I also tried
C#
liSubjectIdDetail= liSubjectIdDetail.Distinct().ToList();

but this too, is not working. Please give me a better solution.
Thanks in advance
Posted

1 solution

Well...it is working - just not the way you think it should.

It is indeed sorting out all the distinct values, but using the default Comparer - so if you haven't written a Comparer for your class it will just use the HashCode method, which will return all the records - since they will be different in some way!

If you want to use Distinct by a property of your class (get all the instances that have different SubjectName values for example) then you need to supply a new Comparer when you do call Distinct.
MSDN can help: http://msdn.microsoft.com/en-us/library/bb338049.aspx[^]
 
Share this answer
 

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