0

I have a List<SelectListItem> that I build from a List that contains videos so I can create a dropdown in the view but I only want to select the unique values, I have tried to select distinct:

List<SelectListItem> items = new List<SelectListItem>();
        foreach (var video in VidModel)
        {
            items.Add(new SelectListItem() { Text = video.Name, Value = video.showName, Selected = false });
        }          
     ViewBag.showName = items.Distinct();

But this returns all the values

Riquelmy Melara
  • 849
  • 2
  • 11
  • 28

1 Answers1

2

You can do a group by on your items.

var uniqueItems= items.GroupBy(s=>s.Value,i=> i, (k ,item) => new SelectListItem
{
    Text = item.First().Text,
    Value=k,
    Selected = item.First().Selected

}).ToList();

I am not sure what you are trying to do . But I think instead of doing this on the SelectListItem collection ,you should be doing on the data you use to build the SelectListItem collection (VidModel ?).

Shyju
  • 214,206
  • 104
  • 411
  • 497