System.Collections.Generic.List ' does

2020-05-11 10:22发布

问题:

I have this error and I do not understand why ..

System.Collections.Generic.List ' does not contain a definition for 'equals'

My list is a List < List < string > >

<tbody>
        <tr>
            @{
                int nbItems = ViewBag.listDonnees.Count ;
                bool colore ;
                for(int cpt = 0; cpt < nbItems; cpt++)
                {
                    colore = false ;

                    if(cpt + 1 < nbItems)
                    {
                        colore = @ViewBag.listDonnees[cpt].equals("#FFFFFF") || @ViewBag.listDonnees[cpt].equals("#FFD700") || @ViewBag.listDonnees[cpt].equals("#FF6347") ;
                    }

                    if(colore)
                    {
                        <td style="background-color:@ViewBag.listDonnees[cpt+1]">@ViewBag.listDonnees[cpt]</td>
                        cpt++;
                    }
                    else
                    {
                        <td>@ViewBag.listDonnees[cpt]</td>
                    }
                }
            }
        </tr>
    </tbody>

I tried to use "==" but I also have this error :

Unable to apply operator '==' to operands of type 'System.Collections.Generic.List ' and 'string'

Thank you for your help

回答1:

Your problem is that: listDonnees[cpt] is a List, you just take the inner list of you List>. If you want to know if the inner List contains the #FFFFFF you need to use .Contains()

listDonnees[cpt].Contains("#FFFFFF")

Or you use a second (nested) for - loop to check every string. By the way: You can check easier by using this:

colore = listDonnees[cpt].Any(s =>new List<String>() {"#FFFFFF", "#FFD700", "#FF6347"}.Contains(s));

So for you problem in particular:

int nbItems = listDonnees.Count ;
var hashCodes = new List<String>() {"#FFFFFF", "#FFD700", "#FF6347"};

for(int cpt = 0; cpt < nbItems; cpt++)
{
    string colorcode = string.Empty;
    if(cpt + 1 < nbItems)
    {
       colorcode = listDonnees[cpt].FirstOrDefault(s => hashCodes.Contains(s));
    }
    if(colorcode != string.Empty)
    {
       <td style="background-color:@colorcode">colorcode</td>
       //cpt++; See below!    
     }
     else
     {
         var str = String.Join(",", listDonnees[cpt]);
         <td>str</td>
     }
     // I Think your cpt++; needs to be here:
     cpt++;
}

I don't know you Model, so you might habe to change your @ViewBag accessing a bit.