gpt4 book ai didi

c# - 使用 LINQ 获取一个 List<> 中的项目,这些项目位于另一个 List<> 中

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:25 25 4
gpt4 key购买 nike

我认为有一个简单的 LINQ 查询可以做到这一点,我只是不确定如何。请参阅下面的代码片段,评论解释了我想做的事情:

class Program
{
static void Main(string[] args)
{
List<Person> peopleList1 = new List<Person>();
peopleList1.Add(new Person() { ID = 1 });
peopleList1.Add(new Person() { ID = 2 });
peopleList1.Add(new Person() { ID = 3 });
peopleList1.Add(new Person() { ID = 4});
peopleList1.Add(new Person() { ID = 5});

List<Person> peopleList2 = new List<Person>();
peopleList2.Add(new Person() { ID = 1 });
peopleList2.Add(new Person() { ID = 4});


//I would like to perform a LINQ query to give me only
//those people in 'peopleList1' that are in 'peopleList2'
//this example should give me two people (ID = 1& ID = 4)
}
}


class Person
{
public int ID { get; set; }
}

最佳答案

var result = peopleList2.Where(p => peopleList1.Any(p2 => p2.ID == p.ID));

关于c# - 使用 LINQ 获取一个 List<> 中的项目,这些项目位于另一个 List<> 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37389027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com