我有一组记录:
type Person =
{
Name : string
Age : int
}
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
与上面的硬编码示例不同,数据集实际上来自数据源(我几乎无法控制)。现在我需要从另一个数据源中减去一组数据。一般来说,第二个源中的数据是匹配的,但偶尔会出现大小写差异:
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
当我尝试从第一个集合中减去第二个集合时,它失败了,因为字符串比较区分大小写:
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> =
set [{Name = "The Doctor";
Age = 1500;}; {Name = "Yoda";
Age = 900;}]
有没有办法对 People
记录的 Name
字段执行不区分大小写的比较?
最佳答案
这是我到目前为止所实现的,尽管可能有更好的方法来做到这一点。
我的解决方案是覆盖 People
记录上的 Equals
函数,以便执行不区分大小写的比较。集合减法使用 Equals
函数来确定两条记录是否相互匹配。通过覆盖 Equals
,我被迫(通过警告和错误)覆盖 GetHashCode
并实现 IComparable
(以及设置 CustomEquality
和 CustomComparison
属性):
[<CustomEquality; CustomComparison>]
type Person =
{
Name : string
Age : int
}
member private this._internalId =
this.Name.ToLower() + this.Age.ToString()
interface System.IComparable with
member this.CompareTo obj =
let other : Person = downcast obj
this._internalId.CompareTo( other._internalId )
override this.Equals( other ) =
match other with
| :? Person as other ->
System.String.Compare( this._internalId, other._internalId ) = 0
| _ -> false
override this.GetHashCode() =
this._internalId.GetHashCode()
然而,这似乎可以解决问题:
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> = set [{Name = "Yoda";
Age = 900;}]
如果您知道更好的解决方案(涉及更少的代码),请发布它而不是对此答案发表评论。我很乐意接受一个不那么冗长、笨拙的解决方案。
关于f# - 使用不区分大小写的比较从集合中减去记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839463/