Skip to main content
 首页 » 编程设计

c#之从满足条件的集合中提取对象

2024年01月24日29jpfss

我想知道您是否知道在 C# 中使用 LINQ 从满足条件的集合中提取对象列表?

我正在尝试从其 ID 在整数列表中匹配的列表中提取 Person 对象的列表。请看下面的代码(我试图拉取所有 ID 在整数列表中的人对象)。

public class Person 
{ 
    public int Id { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 
 
... 
 
var intList = new List<int>() { 1, 2, 3, 4 }; 
var perList = new List<Person> 
{ 
    new Person {Id = 1, FirstName = "Thomas", LastName = "Joseph"}, 
    new Person {Id = 2, FirstName = "Joseph", LastName = "Austin"}, 
    new Person {Id = 3, FirstName = "Lee", LastName = "Hentry"}, 
    new Person {Id = 4, FirstName = "Abraham", LastName = "Tony"} 
}; 

请您参考如下方法:

您可以使用 Where和 Contains方法:

var people = perList 
    .Where(person => intList.Contains(person.Id)) 
    .ToList();