我想在下面的自定義類使用distinct:鮮明的自定義類型
public class RightOperandValue : IEquatable<RightOperandValue>
{
public string Value { get; set; }
public string DisplayName { get; set; }
public int GetHashCode(RightOperandValue obj)
{
int hashValue = Value == null ? 0 : Value.GetHashCode();
int hashDisplayName = DisplayName == null ? 0 : DisplayName.GetHashCode();
return hashValue^hashDisplayName;
}
public bool Equals(RightOperandValue other)
{
if (Value.Equals(other.Value)
&& DisplayName.Equals(other.DisplayName))
{
return true;
}
return false;
}
}
我試圖讓它們是「城市」和「城市」屬性Person.City的不同的值。
我嘗試以下方法:
var values = _context
.Persons
.Select(x=>x.City)
.ToList();
var rovs = values
.Select(x => new RightOperandValue() { DisplayName = x.Trim().ToLowerInvariant(), Value = x.Trim().ToLowerInvariant() })
.Distinct()
.OrderBy(x => x.DisplayName)
.ToList();
return rovs;
其中給出了對顯示名稱和價值的價值「城市」 RightOperandValue的兩個實例。
我知道這似乎是一種迂迴的做事方式,但我最終需要Distinct來處理這個自定義類RightOperandValue。我讀了實施GetHashCode的,等於要做到這一點,但它似乎沒有工作
我讀過這兩次,我仍然不知道你在問什麼。也許它只是我,但你可能想要清除你的問題 – maccettura
我也困惑的問題。我的大腦告訴你看看像.Trim(),.ToUpper()或.String.Compare() –
函數好吧我會盡力清理它。雅這有點不守規矩,對不起。 – pbordeaux