0

I want to select five item one from each category which are having lowest cost, i am getting an error please help me with this

     var packageId = objentity.PackageGalleries.
                Where(p => p.ParentCategory != "Indian" 
                        && p.ParentCategory != "International").
                OrderBy(p => p.PackageCost)
               .GroupBy(p => p.ParentCategory).FirstOrDefault();

it is only selecting one item from one category

In the view i m passing

     @foreach (var item in Model)
        {
            <a href="javascript:;">
                <img src="~/Content/JetJourney/img/@item.FileName" />

                <div>
                    <p>@item.PackageName, Starting Price @item.PackageCost *</p>
                   <br />
                </div>
            </a>
        }
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Richa
  • 41
  • 1
  • 6

1 Answers1

1

You can group the data by ParentCategory and within that group order the grouped data by PackageCost. This should give you the expected output:-

    var packageId = objentity.PackageGalleries
                            .Where(p => p.ParentCategory != "Indian" &&       
                                        p.ParentCategory != "International")
                            .GroupBy(p => p.ParentCategory)
                            .Select(x => x.OrderBy(p => p.PackageCost).FirstOrDefault())
                            .ToList();

Update:

For your issue althought I have never experienced such issue but it may be due to deferred execution of LINQ as per this post. You can force execute the query using ToList() as updated.

Community
  • 1
  • 1
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • @Richa - Really Sorry! Didn't read you question carefully (#IndVsAus you knw ;)). Check updated code. – Rahul Singh Jan 15 '16 at 08:18
  • thankyou, but giving an error "The operation cannot be completed because the DbContext has been disposed.". in the view – Richa Jan 15 '16 at 09:09
  • can you .ToList() method pls?[example](http://stackoverflow.com/questions/21212822/the-operation-cannot-be-completed-because-the-dbcontext-has-been-disposed-using) – Alper Tunga Arslan Jan 15 '16 at 09:26
  • Richa - Please check the update. @AlperTungaArslan - Thanks for the link. – Rahul Singh Jan 15 '16 at 09:41