Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display only unique values in dropdown

 @if (items != null)
{
    <select required class="col-sm-10" 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(); 
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading