简体   繁体   English

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

[英]Filter Distinct Values From List of Custom Type F#

Given a list of integers, we can do the following to obtain the list of distinct values. 给定一个整数列表,我们可以执行以下操作来获取不同值的列表。

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

However, in my case I have a list of a custom type defined as follows: 但是,在我的情况下,我有一个自定义类型的列表,定义如下:

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 

Next I have a list defined as follows: 接下来我有一个如下定义的列表:

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

Now I want to filter this list to obtain only the unique values (a value is unique if it has a unique listingId ). 现在我想过滤此列表以仅获取唯一值(如果值具有唯一的listingId则该值是唯一的)。 I could do this the naive way and add all the listingId to a list of strings, perform the distinct operation on the list of strings and then extract the listings with the ids in the distinct list, but I think there has to be a better approach. 我可以用天真的方式做到这一点,并将所有的listingId添加到字符串列表中,对字符串列表执行不同的操作,然后使用不同列表中的ID提取列表,但我认为必须有更好的方法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM