首页 > 解决方案 > 在 for 循环中将 string[] 与 string[] 进行比较

问题描述

我正在尝试比较 2strings[]并显示为检查过的类似项目。当要比较的第一个列表具有单个值但不在列表中时,它工作正常 ( string[])

@functions {
    private static string[] GeoArea
    {
        get
        {
            string[] geoArea = {"Horse", "Cat", "Dog", "Dear", "Donkey", "Lamb"};
            return geoArea;
        }
    }

    string[] geoArea = GeoArea;
}

@{
    string[] blablab = {"Cat", "Dog", "Dear"};
    var results = string.Join(",", blablab);
}

@{
    for (int s = 0; s < geoArea.Length; s++)
    {
        if (results != geoArea[s])
        {
            <input class = "check_boxes" id = "@s.ToString()" name = "District" type = "checkbox" value = "@geoArea[s]"/>
            @geoArea[s]
        }
        else
        {
            <div style = "background-color: red; min-height: 50px;" >
                <input class = "check_boxes" id = "@s.ToString()" name = "District" type = "checkbox" value = "@geoArea[s]" checked = "checked"/>
                @geoArea[s]
            </div>
        }
    }
}

结果是所有项目都未教会

谢谢。

标签: c#razorasp.net-core-mvc

解决方案


你想在Contains这里使用https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=net-5.0

@functions {
    private static string[] GeoArea
    {
        get
        {
            string[] geoArea = {"Horse", "Cat", "Dog", "Dear", "Donkey", "Lamb"};
            return geoArea;
        }
    }
    string[] geoArea = GeoArea;
}

@{
    string[] blablab = {"Cat", "Dog", "Dear"};
}

@{
    for (int s = 0; s < geoArea.Length; s++)
    {
            <div style="@(blablab.Contains(geoArea[s]) ? "background-color: red; min-height: 50px;" : "" )" >
                <input class = "check_boxes" id="@s.ToString()" name="District" type="checkbox" value="@geoArea[s]" @(blablab.Contains(geoArea[s]) ? "checked" : "" ) />
            @geoArea[s]
            </div>
    }
}

推荐阅读