Linq Contains and Distinct
I have the following 3 tables with their fields
Books(Id_Book | Title | Year)
Book_Themes (Id | Id_Book| Id_Theme) Themes (Id_Theme| Title)I also have an Giud array with Id_Themes
Guid [] themesArray = new Guid []{new Guid("6236c491-b4ae-4a2f-819e-06a38bf2cf41"), new Guid("06586887-7e3f-4f0a-bb17-40c86bfa76ce")};
I'm trying to get all Books containing any of the Theme_Ids from the themesArray
This is what I have so far which is not working. Not sure how to use Contains in this scnenario.
int index = 1; int size= 1开发者_StackOverflow社区0;
var books = (from book in DB.Books
join bookWThemes in DB.Book_Themes
on book.Id_Book equals bookWThemes.Id_Book
where themesArray.Contains(bookWThemes.Id_Theme)
orderby book.Year
select book)
.Skip((index - 1) * page)
.Take(size);
I'm getting an error on themesArray.Contains(bookWThemes.Id_Theme): System.Guid[] does not contain a definition for Contains. Also I'm not sure where to put the Distinct
****UPDATE****
noticed that my Model had Id_Theme as nullable... I changed the DB and didn't reflect the changes on my model. So to answer the question if it's nullable just change the Contains line to themesArray.Contains(bookWThemes.Id_Theme.Value)... and with this change it works.
Thanks for all the help!.
It's strange that your LINQ query is breaking down on .Contains. All three of the forms IEnumerable<> and List<> work for me.
[Test]
public void Test43()
{
var a = new List<Guid>(){new Guid(),new Guid(),new Guid()};
a.Contains(new Guid()); // works okay
var b = (IEnumerable<Guid>)a;
b.Contains<Guid>(new Guid()); // works okay
b.Contains(new Guid()); // works okay
}
For the "distinct" question, put the call here:
select book)
.Distinct() // <--
.Skip((index - 1) * page)
Try casting the Guid[]
to List<Guid>
and then you can use Contains on it.
where themesArray.ToList().Contains(bookWThemes.Id_Theme)
精彩评论