Home > OS >  Hide Elements from Html.DropDownListFor() that share the same name
Hide Elements from Html.DropDownListFor() that share the same name

Time:10-31

im new to C# and im trying to hide a couple of itens from an html.dropdownlist that i created, i have a dummy list that i created in sql and linked to my project, right now everything works but i have values in my table that share the same data which includes the same name, im trying to keep those values on the sql database but change my view in a way that it would hide duplicates in the dropdownlist.

this is my html method that is working perfectly but shows every item in the database including multiple entries with the same name.

@Html.DropDownListFor(m => m.TestId, new SelectList(Model.TestModel, "TestId", "TestName"))

i've tried using a .Distinct() which was one of the most common solutions i found while researching on the topic but im not sure how to apply it to my code since the following two versions didnt work.

@Html.DropDownListFor(m => m.TestId, new SelectList(Model.TestModel.Select(x => x.model.TestName).Distinct()), "TestId", "TestName"))
`@Html.DropDownListFor(m => m.TestId, new SelectList(Model.TestModel, "TestId", "TestName").Distinct())`

i've also tried using jquery to hide elements from the list but i wasnt able to hide duplicates and ended up either hiding every element that shares a name or having to individually target every element i wanted to hide from the table.

i would really appreciate if someone is able to give me a direction on how to solve this, thanks in advance!

CodePudding user response:

I think you want something like this

@Html.DropDownListFor(m => m.TestId, new SelectList(Model.TestModel.GroupBy(x => x.TestName).Select(x => x.FirstOrDefault()), "TestId", "TestName"))

Here's a short console program to illustrate what's going on:

var list = new List<TestModel>();

list.Add(new TestModel { TestId = 1, TestName = "abc" });
list.Add(new TestModel { TestId = 2, TestName = "mno" });
list.Add(new TestModel { TestId = 3, TestName = "xyz" });
list.Add(new TestModel { TestId = 4, TestName = "abc" });

// foreach (var i in list)
foreach (var i in list.GroupBy(x => x.TestName).Select(x => x.FirstOrDefault()))
{
    Console.WriteLine(String.Format("TestId {0}, TestName {1}", i.TestId, i.TestName));
}

Compared to the commented out foreach line, the longer foreach line uses GroupBy and FirstOrDefault to group entries with the same TestName value together and then only select the first one from each "match group".

Notice that the entry with TestId = 1 made it through the filter but the entry with TestId = 4 did not. You didn't really specify which TestId value you wanted to preserve.

  • Related