2011-12-20 144 views
0

Q選擇:如何從列表過濾通過

我有對象的列表如下:

List<object> entities = GetallEntities();

在前面的列表中的第一個對象是:List<Books>

現在我想獲得這id

存在以下列表中的所有書籍:

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

回答

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

非常感謝.... – 2011-12-20 10:34:22

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

非常感謝.... – 2011-12-20 10:35:15