I am storing a list of select items in my view model. When adding the correct select items i get them from a list stored in a spreadsheet, some of which are duplicates. I want to eliminate these duplicates and have the following code to do so.
//Fill with all the install locations
foreach (App y in applications)
{
//Check if the app has a server listed
if (y.Server != "")
{
SelectListItem ItemToAdd = new SelectListItem { Text = y.Server, Value = y.Server };
//Check if the the item has already been added to the list
if (!vm_modal.serverLocations.Contains(ItemToAdd))
{
vm_modal.serverLocations.Add(ItemToAdd);
}
}
}
However this is not working as it is just adding everything so there are a lot of duplicates. I don't know if contains works differently because I'm not just dealing with regular strings or something like that.
In this instance, as you are using the same string for Text
and Value
, you can iterate through your source, and add non-duplicate values to a simple List<string>
before adding all of the checked values to your select list.
List<string> result = new List<string>();
foreach (App y in applications)
{
//Check if the app has a server listed and for duplicates
if (y.Server != "" && !result.Contains(y.Server))
{
result.Add(y.Server);
}
}
result.ForEach(x => vm_modal.serverLocations.Add(
new SelectListItem(){Text = x, Value = x}));
for a "one liner" of what ste-fu presented you can write
vm_modal.serverLocations
.AddRange(applications
.Where(app => app.Server != "")
.Select(app => app.Server)
.Distinct()
.Select(server => new SelectListItem{ Text = server, Value = server }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.