开发者

LINQ query to find common strings between two collections

开发者 https://www.devze.com 2023-01-24 03:12 出处:网络
Given the following distinct two collections: IQueryable<Book> allBooks = context.Books.Where(b => b.UserID == hostID);

Given the following distinct two collections:

IQueryable<Book> allBooks = context.Books.Where(b => b.UserID == hostID);

var visBookTitles = context.Books.Where(b => b.UserID == visitorID)
.Select(b =>b.Title.ToLower()).ToList();

What would be the most efficient way (using method syntax, preferably) to return all the books from allBook开发者_StackOverflow社区s that share a common title with any of the titles from visBookTitles ?


Use Intersect() if the items in the collections should be considered equal or Join() if they only share certain properties. In your case, you're intersecting books vs titles so Join() is most appropriate.

var query = allBooks.Join(visBookTitles,
                          book => book.Title,
                          title => title,
                          (book, title) => book);


Like this:

var bookTitles = new HashSet<string>(visBookTitles, StringComparer.OrdinalIgnoreCase);
var someBooks = allBooks.AsEnumerable().Where(b => bookTitles.Contains(b.Title));

You should also get rid of the ToLower call. (StringComparer.OrdinalIgnoreCase is faster and handles messy Unicode situations)

0

精彩评论

暂无评论...
验证码 换一张
取 消