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

时间:2011-12-20 10:00:42

标签: c# asp.net linq list casting

问:

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

List<object> entities = GetallEntities();

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

现在我想获得所有id

的书籍

存在于以下列表中:

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

2 个答案:

答案 0 :(得分:2)

假设您的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);

答案 1 :(得分:2)

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));