开发者

LINQ query to find common strings between two collections

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜