如何通过 IN 从列表筛选中进行选择

本文关键字:行选 选择 筛选 列表 何通过 IN | 更新日期: 2023-09-27 18:18:35

Q:

我有一个这样的对象列表:

List<object> entities = GetallEntities();

上一个列表中的第一个对象是:List<Books>

现在我想得到所有id的书

存在于以下列表中:

List<string> BookIds = new List<string>();

如何通过 IN 从列表筛选中进行选择

假设您的Books类具有Id属性,并且一个实例表示一本书:

// Get the first element of your entity-list which is of type `List<Books>`
List<Books> bookList = entities.OfType<List<Books>>().First();
List<string> BookIds = new List<string>();
// fill your id list here ...
// filter your books by the list of ids
IEnumerable<Books> filteredBooks = 
               bookList.Where(b => BookIds.Any(id => id == b.Id);
public class Book
{
    public string id { get; set; }
}

List<object> entities = new List<object> { new Book { id = "1" }, new Book { id = "2" } };
List<string> bookIds = new List<string> { "2" };
IEnumerable<object> books = entities.Where(e => e is Book && bookIds.Contains(((Book)e).id));