Home > Software engineering >  Display only unique values in dropdown
Display only unique values in dropdown

Time:11-14

 @if (items != null)
{
    <select required  bind="searchByLocation" @onchange="LocationOnChange">
        <option value="" disabled selected hidden>Search By Location</option>
        @foreach (var r in items)
        {
            <option value="@r.location">@r.location</option>
        }
    </select>
}

Below is my class and working code that displays location in the dropdown (but not unique values).

public class DisplayItem
{     
    public string itemKey { get; set; }
    public string id { get; set; }
    public string location{ get; set; }       
} 

List<DisplayItem> items = new ();
private DisplayItem[] locationDropDown ;

protected override async Task OnInitializedAsync()
{
items = (await ItemService.GetItems())
    .GroupBy(x => x.ItemKey)
    .Select(x => new DisplayItem
    {
        ItemKey = x.Key,
        Id = x.FirstOrDefault(y => y.Key == "Id")?.Value,
        Location = x.FirstOrDefault(y => y.Key == "Location")?.Value,
    })
    .ToList();

// locationDropDown = items.Select(x => x.location).Distinct().ToArray(); 

}

Below helps filter records by choosing a location from dropdown. But same country is displayed many times. I want to display only unique values in dropdown. Thank you.

private DisplayItem[] result;
string searchByLocation;

 private async Task LocationOnChange(ChangeEventArgs args)
{
    searchByLocation = (string)args.Value;
    await LocationChanged();
}

private async Task LocationChanged()
{
    result= items.Where(part => part.location == searchByLocation).ToArray(); 
}

CodePudding user response:

The foreach loop in the razor file is based on items which do not have unique locations. So, change the loop to

@foreach (var l in items.Select(x => x.location).Distinct())
{
    <option value="@r.location">@l</option>
}

or base the loop on a collection of unique locations instead of items.

CodePudding user response:

you probably need to add Distinct to your LocationChanged method. Something like this:

private async Task LocationChanged()
{
    result= items.Where(part => part.location == searchByLocation).Distinct().ToArray(); 
}
  • Related