【问题标题】:Linq - Select distinct objects [duplicate]Linq - 选择不同的对象[重复]
【发布时间】:2018-11-13 18:12:50
【问题描述】:

我正在尝试通过它们的值提取不同的对象,以获得我在 .csv 中的唯一 CurrencyISO。

public List<CurrencyDetail> InitGSCheckComboCurrency()
{
    var lines = File.ReadAllLines("Data/AccountsGSCheck.csv");
    var data = (from l in lines.Skip(1)
                let split = l.Split(',')
                select new CurrencyDetail
                {
                    ISOName = split[3],
                    ISOCode = split[3]
                }).Distinct();

    List<CurrencyDetail> lstSrv = new List<CurrencyDetail>();
    lstSrv = data.ToList();

    return lstSrv;
}

但是,distinct 函数对此不起作用,我最终会出现重复。

【问题讨论】:

  • 错字? ISOName 和 ISOCode 都是 third - split[3] - items?
  • 重要的区别,你想要不同的值还是唯一的值?例如,如果您有 1,2,2,3,则不同的值为 1,2,3,但唯一的值为 1,3。

标签: c# linq


【解决方案1】:

您需要定义 CurrencyDetail 的 Equals 和 GetHashCode 才能执行您想要的操作。快速而肮脏的解决方案:

var data = (from l in lines.Skip(1)
           let split = l.Split(',')
           select new
           {
               ISOName = split[3],
               ISOCode = split[3]
           }).Distinct()
           .Select(x => new CurrencyDetail
           {
               ISOName = x.ISOName,
               ISOCode = x.ISOCode
           };

匿名类型(第一个new { ... })会自动定义明智的Equals() 和GetHashCode()。通常我不会这样做,因为您正在创建对象然后丢弃它们。出于这个原因,它是一个快速而肮脏的解决方案。

请注意,您使用了两次split[3]... 出错了吗?

现在,CurrencyDetail 的完全等价版本可能是:

public class CurrencyDetail : IEquatable<CurrencyDetail>
{
    public string ISOName { get; set; }
    public string ISOCode { get; set; }

    public override bool Equals(object obj)
    {
        // obj is object, so we can use its == operator
        if (obj == null)
        {
            return false;
        }

        CurrencyDetail other = obj as CurrencyDetail;

        if (object.ReferenceEquals(other, null))
        {
            return false;
        }

        return this.InnerEquals(other);
    }

    public bool Equals(CurrencyDetail other)
    {
        if (object.ReferenceEquals(other, null))
        {
            return false;
        }

        return this.InnerEquals(other);
    }

    private bool InnerEquals(CurrencyDetail other)
    {
        // Here we know that other != null;

        if (object.ReferenceEquals(this, other))
        {
            return true;
        }

        return this.ISOName == other.ISOName && this.ISOCode == other.ISOCode;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            // From http://stackoverflow.com/a/263416/613130
            int hash = 17;
            hash = hash * 23 + (this.ISOName != null ? this.ISOName.GetHashCode() : 0);
            hash = hash * 23 + (this.ISOCode != null ? this.ISOCode.GetHashCode() : 0);
            return hash;
        }
    }
}

有了这个,您可以使用您的代码所使用的Distinct()。

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2013-10-24
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多