【问题标题】:Select distinct values from a list using LINQ使用 LINQ 从列表中选择不同的值
【发布时间】:2013-07-13 17:01:47
【问题描述】:

我想使用 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();

【问题讨论】:

  • 在特定列上不同?

标签: asp.net linq


【解决方案1】:

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

 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

【讨论】:

    【解决方案2】:

    按照您编写的方式,您只会剪掉完全相同的重复行。你的结果中有任何一个吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多