DudeThatCodes DudeThatCodes - 1 month ago 7
C# Question

How to create list of items from another list

How can I create a list from items in another list?

List<Post> postList = db.Posts.Where(u => u.PostId == postId).ToList();
List<PostView> viewList = db.PostViews.Where(u => u.PostId **** is equal to PostId within postList**** );


I used the ****'s to show where my understanding falls apart.

Answer

You can select the Id's from the other list, then see if that list contains your current Id. Although, I would generate the list of Id's first. Assuming your Id's are of type int:

List<Post> postList = db.Posts.Where(u => u.PostId == postId).ToList();
List<int> postIds = postList.Select(u => u.PostId).ToList();
List<PostView> viewList = db.PostViews.Where(u => postIds.Contains(u.PostId)).ToList();