简体   繁体   English

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

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

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. 我不知道contains的工作方式是否有所不同,因为我不仅在处理常规字符串或类似的东西。

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. 在这种情况下,由于您对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}));

for a "one liner" of what ste-fu presented you can write 可以写出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