Reputation: 4728
I want to compare 2 collections. One of these is a List<string>
and the other is a List<Book>
. Book has a Isbn property of type string
, and I want write something like that :
List<string> isbnBooks= new List<string> {"978-1933988276", "978-0321146533", "3"};
List<Book> books = new List<Book>();
books.Add(new Book { Isbn="978-1933988276", Name="The Art of Unit Testing"});
books.Add(new Book { Isbn="978-0321146533", Name="TDD By Example"});
books.Add(new Book { Isbn="978-0321503626", Name="Growing Object-Oriented Software"});
// What I want to write
var intersectedBooks = books.Intersect(books, isbnBooks, (book, isbn) => book.Isbn == isbn));
I would like specify equality in the method. Is it possible ? Or should I mandatory create a BookComparer which implements IEqualityComparer interface ?
Regards,
Florian
Upvotes: 0
Views: 989
Reputation: 14086
Or, you could always do:
var intersectedBooks = books.Select(book=>book.Isbn).Intersect(isbnBooks);
Upvotes: 2
Reputation: 1501656
Intersect
simply doesn't work with different collection types. In this case it looks like it would be simpler to write:
HashSet<string> isbns = new HashSet<string> isbnBooks();
var intersectedBooks = books.Where(book => isbns.Contains(book.Isbn));
Or you could just do a join, of course:
var knownBooks = from book in books
join isbn in isbnBooks on book.Isbn equals isbn
select book;
(The two approaches are broadly equivalent.)
Upvotes: 3