来自linq的不同值 [英] distinct values from the linq

查看:69
本文介绍了来自linq的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<IncomeStatement> dtincome = 
(from emp in IS
 where emp.dataItemId == item.dataItemId

  select new IncomeStatement
      {

     fiscalYear = emp.fiscalYear,

 }).OrderByDescending(i => i.fiscalYear).Distinct().ToList();







in上面的查询不会检索不同的值。如何可能




in the above query does not retrieve the distinct values.How its possible

推荐答案

您确定生成的IncomeStatement重复项是否产生相同的哈希值?您可能必须编写自己的相等比较器而不是依赖于默认值。



Are you sure that the resulting IncomeStatement duplicates produce the same hash? You may have to write your own equality comparer instead of relying on the default.

public partial class IncomeStatement:IEqualityComparer<IncomeStatement>, IEquatable<IncomeStatement>{
    
    public override int GetHashCode(IncomeStatement item)
    {
        int hash = item.Id ^ item.PropertyA ^ item.etc;
        return hash.GetHashCode();
    }

    public override bool Equals(IncomeStatement x, IncomeStatement y)
    {
        return y.Equals(y);
    }
    public bool Equals(IncomeStatement other)
    {
        return (this.Id==other.Id 
             && this.PropertyA == other.PropertyA 
             && this.ect==other.ect);
    }
}





您还可以尝试使用GroupBy来证明您所比较的元素确实是重复的:





You could also try GroupBy to prove that the elements your are comparing are indeed duplicated:

List<IncomeStatement> dtincome = IS
   .Where(emp=>emp.dataItemId == item.dataItemId)
   .GroupBy(emp=>new IncomeStatement{fiscalYear = emp.fiscalYear})
   .Select(g=>g.key) //instead of default distinct
   .OrderByDescending(i => i.fiscalYear) //always best to do sorting last
   .ToList();


这篇关于来自linq的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆