使用LINQ从列表中选择不同的值

时间:2013-07-13 07:46:35

标签: asp.net linq

我希望使用linq从数据库中选择不同的firstName列
我的班级是:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你写它的方式只能得到精确的重复线条。你在结果中得到任何一个吗?

如果您需要对特定列进行区分,请查看以下答案:Distinct By specific property