无法检查列表是否包含 C# 中的 select 项

Can't check whether a list contains a select item in C#

我正在我的视图模型中存储 select 项的列表。添加正确的 select 项目时,我从存储在电子表格中的列表中获取它们,其中一些是重复的。我想消除这些重复项并使用以下代码来执行此操作。

        //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);
                }
            }
        }

但是这不起作用,因为它只是添加所有内容,所以有很多重复项。我不知道 contains 的工作方式是否不同,因为我不只是处理常规字符串或类似的东西。

在这种情况下,由于您对 TextValue 使用相同的字符串,您可以遍历源代码,并将非重复值添加到简单的 List<string>在将所有选中的值添加到 select 列表之前。

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}));

"one liner" 你可以写

vm_modal.serverLocations
    .AddRange(applications
               .Where(app => app.Server != "")
               .Select(app => app.Server)
               .Distinct()
               .Select(server => new SelectListItem{ Text = server, Value = server }));