Kotlin-通过与属性列表进行比较来过滤对象列表 [英] Kotlin - filtering a list of objects by comparing to a list of properties

查看:712
本文介绍了Kotlin-通过与属性列表进行比较来过滤对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上课的人:

class Person(var fullName: String, var nickname: String, var age: Int)

在我的代码中,有时我会有一个Person对象列表和一个昵称列表.

In my code, at some point I have a List of Person objects, and a list of nicknames.

var people: List<Person> = listOf(
  Person("Adam Asshat", "dontinviteme", 21),
  Person("Bob Bowyer", "bob", 37),
  Person("Emily Eden", "emily", 22)
)

var invitedToParty: List<String> = listOf("bob", "emily")

现在,我想通过使用lambda来获得仅包含Bob和Emily的列表,但是我不确定如何在Kotlin中使用它.

Now I want to get a List with only Bob and Emily by using lambda's, but I'm not sure how I'd go about it in Kotlin.

var invitedPeople: List<Person> = // a lambda that results in a list containing only Bob and Emily's objects

在C#中,我可能会使用LINQ和.where()方法与== any()结合使用,但Kotlin似乎从我发现的内容中没有类似的东西.

In C# I'd probably use LINQ and a .where()-method combined with an == any() but Kotlin doesn't seem to have anything like that from what I've found.

在Kotlin lambda's里甚至有可能吗?

Is this even possible in Kotlin lambda's?

推荐答案

在C#中,您需要这样做:

In C# you'd do:

people.Where(p => invitedToParty.Any(s => s == p.nickname));

就像在Kotlin中一样,您将使用filter,它与Where类似,而any则说明了这一点:

Likewise in Kotlin, you'd use filter which is like Where and any speaks for it self:

people.filter { p -> invitedToParty.any { it == p.nickname } }

或使用contains:

people.filter { invitedToParty.contains(it.nickname) }

这篇关于Kotlin-通过与属性列表进行比较来过滤对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆