Apratim Bhattacharya
Apratim Bhattacharya

Reputation: 135

select N items from DB but display only k (where k<N) in ASP.NET MVC

I have the following code where I am selecting 100 items from the db, but would like to display only 5 in the dropdown. The .Take method does not seem to work.

   HeatService heatService = new HeatService();
        List<HeatDropdownOption> availableHeats = heatService.GetHeats()
                                               .Where(h => h.ComponentType.Equals(componentType.ToString()))
                                               .OrderByDescending(h => h.Date)
                                               .Take(Constants.NMostRecentHeats)
                                               .Select(h => new HeatDropdownOption(h))
                                               .ToList();

        //HeatDropdown = new MultiSelectList(availableHeats, "ID", "Label", selectedHeats.Select(h=>h.ID).ToList());
        HeatDropdown = new MultiSelectList(availableHeats, "ID", "Label", selectedHeats.Take(5).Select(h => h.ID).ToList());

Upvotes: 1

Views: 25

Answers (1)

Usman
Usman

Reputation: 4703

if you look at the overloads of MultiSelectList the 4th overload is to select items in the list and the 1st overload is to set the data to dropdown so we can use .Take(5) to filter the data before populating it in the dropdown. so if you want to display only 5 in dropdown use take like this

    HeatDropdown = new MultiSelectList(availableHeats.Take(5), "ID", "Label");

it will display the first 5 items from the availableHeats

Upvotes: 1

Related Questions