2017-02-21 41 views
0

鲜明不给不同的一行表鲜明不给不同的一行表

ObjectParameter statusCode = new ObjectParameter("StatusCode", typeof(int)); 
ObjectParameter statusMessage = new ObjectParameter("StatusMessage", typeof(string)); 
return Context.p_Countries_List(userName, statusCode, statusMessage) 
       .Select(c => new Countries_List_ResultModel() 
      { 
       currency = c.currency 
      }).Distinct().ToList(); 
+1

....那命名约定,为什么你放弃标准的C#之一? :) –

+0

'货币'是唯一设置的属性? – Andrew

回答

-1

我找到了答案,这是行得通的。

 ObjectParameter statusCode = new ObjectParameter("StatusCode", typeof(int)); 
     ObjectParameter statusMessage = new ObjectParameter("StatusMessage", typeof(string)); 
     return Context.p_Currencies_List(userName, statusCode, statusMessage).Distinct().Select(c => new Countries_List_ResultModel() 
     { 
      currency = c 
     }).ToList(); 
1

您必须覆盖Equals所以Distinct知道如何从另一个告诉一个实例。

public class Countries_List_ResultModel 
{ 
    public override bool Equals(object obj) 
    { 
     var item = obj as Countries_List_ResultModel; 

     if (item == null) 
     { 
      return false; 
     } 

     return true; // Add the appropriate logic. 
    } 

    public override int GetHashCode() 
    { 
     // Return the hashcode to quickly identify different instances. 
     return this.currency.GetHashCode(); 
    } 
} 

更多信息here

0

Distinct方法的两个重载:

Distinct<TSource>(this IEnumerable<TSource> source); 
Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer); 

显然,您所使用的使用默认的相等比较器对值进行比较的第一个。引用类型的默认相等比较器通过引用来比较它们,这就是为什么所有new Countries_List_ResultModel对于比较器都不相同的原因。 您可以创建自己的自定义比较器来检查currency的等同性,并使用以IEqualityComparer<TSource> comparer作为参数的超载。

 return Context.p_Countries_List(userName, statusCode, statusMessage) 
       .Select(c => new Countries_List_ResultModel() 
      { 
       currency = c.currency 
      }).Distinct(new MyCustomComparer()).ToList(); 

    public class MyCustomComparer : IEqualityComparer<Countries_List_ResultModel> 
    { 
     public bool Equals(Countries_List_ResultModel x, Countries_List_ResultModel y) 
     { 
      if (x == y) return true; 
      if (x == null || y == null) return false; 
      return x.currency == y.currency; 
     } 

     public int GetHashCode(Countries_List_ResultModel obj) 
     { 
      if (obj == null) return 0; 
      return obj.currency.GetHashCode(); 
     } 
    }