从自定义类型F#列表中筛选出不同的值

时间:2018-02-25 16:50:12

标签: .net list f# sequence

给定一个整数列表,我们可以执行以下操作来获取不同值的列表。

let myList = [ 1; 2; 2; 3; 4; 3 ]
let distinctList = myList |> Seq.distinct |> List.ofSeq

但是,在我的情况下,我有一个定义如下的自定义类型列表:

type Listing(fromDate:NSDate, toDate:NSDate, pricePerNight:int, landlordId:String, landlordName:String, listingId:String, pic1url:NSUrl, pic2url:NSUrl, pic3url:NSUrl, pic4url:NSUrl, pic5url:NSUrl, postcode:String, latitude:Double, longitude:Double, location:String, partnername:String,partnerid:String) = 
 member this.fromDate : NSDate = fromDate
 member this.toDate : NSDate = toDate
 member this.pricePerNight : int = pricePerNight
 member this.landlordId : String = landlordId
 member this.landlordName : String = landlordName
 member this.listingId : String = listingId
 member this.pic1url : NSUrl = pic1url
 member this.pic2url : NSUrl = pic2url
 member this.pic3url : NSUrl = pic3url
 member this.pic4url : NSUrl = pic4url
 member this.pic5url : NSUrl = pic5url
 member this.postcode : String = postcode
 member this.latitude : Double = latitude
 member this.longitude : Double = longitude
 member this.location : String = location
 member this.partnername : String = partnername 
 member this.partnerid : String = partnerid 

接下来我有一个如下定义的列表:

let mutable listings : List<Listing> = List.Empty

现在我想过滤此列表以仅获取唯一值(如果值具有唯一listingId,则该值是唯一的)。我可以用天真的方式做到这一点并将所有listingId添加到字符串列表中,对字符串列表执行不同的操作,然后使用不同列表中的ID提取列表,但我认为必须是一个更好的方法。

1 个答案:

答案 0 :(得分:5)

您可以将Seq.distinctBy与lambda函数一起使用,以获得唯一性所需的值:

listings |> Seq.distinctBy (fun l -> l.listingId)