Select separate values ​​from a list using LINQ

advertisements

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();


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