2

我想用 linq 从数据库中选择不同的名字列,
我的班级是:

public partial class user
{

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

我使用下面的代码,但返回完整列表。

var query = (from user _db.Users
                     select user).Distinct().OrderBy(u=>u.firstName).ToList();
4

2 回答 2

2

要从自定义对象列表中返回不同的值,您需要在类中实现IEquatable<T>接口。user

 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. 
 }

  }`

更多示例请访问:http: //msdn.microsoft.com/en-us/library/bb348436.aspx

于 2013-07-13T07:53:02.813 回答
0

你写它的方式你只会得到精确的重复行。你的结果中有任何一个吗?

如果您需要在特定列上区分,请查看此答案:Distinct By specific property

于 2013-07-13T07:50:10.503 回答