Linq - 选择不同的对象

时间:2018-06-04 11:57:07

标签: c# linq

我正在尝试按其值提取不同的对象,以便在CurrencyISO中拥有唯一的.csv

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;
}

然而,不同的功能对此不起作用,我最终会重复。

1 个答案:

答案 0 :(得分:1)

您需要定义Equals的{​​{1}}和GetHashCode来执行您想要的操作。快速而肮脏的解决方案:

CurrencyDetail

匿名类型(第一个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; } } }