繁体   English   中英

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

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

我在视图模型中存储了选择项的列表。 当添加正确的选择项时,我会从存储在电子表格中的列表中获取它们,其中一些是重复项。 我想消除这些重复项,并使用以下代码来消除。

        //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>然后再将所有选中的值添加到选择列表中。

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

可以写出Ste-fu呈现的内容的“一个衬里”

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM