0

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.

1
  • See msdn for examples using linq. I think in some cases you will need to use the join method to combine list. In some cases yafter the WHERE you will need to use SELECT method to get only some properties of a class instead of the entire class. code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b Commented Oct 14, 2016 at 17:46

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

4 Comments

It would be better if postIds were a HashSet
All the answers seem close, but yours and abion come back with the following error: Cannot implicitly convert type 'System.Linq.IQueryable<App.Models.PostView>' to 'System.Collections.Generic.List<App.Models.PostView>'. An explicit conversion exists (are you missing a cast?) Any ideas?
@DudeThatCodes You were declaring a List<PostView> but returning an IQueryable. My fault I didn't catch that. Just updated my answer.
I feel like everyone that responded was pretty close, but yours worked the best for me. Thanks for the help.
0

Give this a shot:

List<PostView> viewList = db.PostViews.Where(
    u => postList.Any(p => p.PostId == u.PostId));

Comments

0
List<PostView> viewList = db.PostViews.Where(u => postList.Any(pl=>pl.postId == u.postId));

But you should be able to do this in one shot:

List<PostView> viewList = db.PostViews.Where(u => u.Post.postId == postId);

or even

List<PostView> viewList = db.PostViews.Where(u => u.PostId == postId);

It seems a postview has a post. You shouldn't have to get a list of posts first and then get a list of views from that list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.