2

i want select distinct firstName's column from Database with linq
my class is:

public partial class user
{

    public string firstName{ get; set; }
    public string lastName{ get; set; }
    public int    dgree{ get; set; }
    public string class{ get; set; }
}

i using below code but return full list.

var query = (from user _db.Users
                     select user).Distinct().OrderBy(u=>u.firstName).ToList();
1
  • Distinct on a specific column? Commented Jul 13, 2013 at 8:00

2 Answers 2

2

To return distinct values from a list of custom objects you need to impelement the IEquatable<T> interface in the user class.

 public partial class user : IEquatable<user>
 {

public string firstName{ get; set; }
public string lastName{ get; set; }
public int    dgree{ get; set; }
public string class{ get; set; }

 public bool Equals(Product other)
{

   //check if the objects are the same based on your properties:
   //example 
    if (firstName == other.firstName) 
            return true; //then i assume they're equal and return true. You can check here all your properites that make an object unique. 

   return false; 
}

public override int GetHashCode()
 {
          // If Equals() returns true for a pair of objects  
// then GetHashCode() must return the same value for these objects. 
 }

  }`

More examples at : http://msdn.microsoft.com/en-us/library/bb348436.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

The way you wrote it you get only exact duplicate lines cut. do you get any of them in your result ?

if you need to distinct on specific column check out this answer: Distinct By specific property

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.