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();
Ramin Asadi
  • 281
  • 2
  • 17

2 Answers2

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

Dan Dinu
  • 32,492
  • 24
  • 78
  • 114
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

Community
  • 1
  • 1
Dani
  • 14,639
  • 11
  • 62
  • 110