Rubia Gardini
Rubia Gardini

Reputation: 815

How to perform this foreach loop I need?

I have a web app that has a Diary. In this Diary, I can post updates and my friends can see it and vote. They can like, unlike, etc.

So, I take the 6 last posts, and I also have to take the votes (like, unlike, etc) for each post.

My problem is how could I get this impression votes related to the Diary post? I tried this:

var impressions = "";

foreach (var item in diaryPosts)
{
    impressions = (from i in db.Impressions
                   select new ImpressionsSet
                   {
                       ImpressionID = i.ID,
                       ImpressionTitle = i.Impression,
                       ImpressionNum = i.DiaryImpressions.Count(d => d.DiaryPostsID == item.PostID)
                   }).ToList();
}

But with this approach, I get the error:

Cannot implicity convert type 'System.Collections.Generic.List<...>' to 'string'

I would like this var 'impressions' get all impressions related to these 6 last posts I show in my page.

So, foreach Diary post I have, I would have another foreach to my impressions and its Counts but on the other hand, this var 'impressions' would have 2 foreach loops inside, one for each post, and one foreach impression.

Could anyone help me with that with a sample for my Controller and for my razor View? Is my explanation clear enough? Thank you in advance.

Upvotes: 0

Views: 78

Answers (3)

Richard Anthony Hein
Richard Anthony Hein

Reputation: 10650

    var allimpressions = 
    from dp in diaryPosts
    from i in dp.Impressions
    let count = i.DiaryImpressions.Count (di => di.DiaryPostsID == dp.PostID)
    select new { ImpressionID = i.ID, ImpressionTitle = i.Impression, ImpressionNum = count };

Upvotes: 0

punker76
punker76

Reputation: 14611

try this one

var allimpressions = diaryPosts.SelectMany(dp => {
         return (from i in dp.Impressions
          select new ImpressionsSet
          {
           ImpressionID = i.ID,
           ImpressionTitle = i.Impression,
           ImpressionNum = i.DiaryImpressions.Count(d => d.DiaryPostsID == dp.PostID)
          }).ToList();
         });

Upvotes: 1

Piotr Perak
Piotr Perak

Reputation: 11098

impressions is of type string.

var impressions = "";

And you try to assign list to that variable.

Change it to

List<ImpressionSet> impressions;

Upvotes: 2

Related Questions