How to check if a specific value exists (string) in a list in C #?

4

I'm trying to set up an input select multiple and leave checked the options that are already present in a certain list.

I'm a beginner in C # so the logic of what I need would be something like this: (Note that I'm using Razor)

Sorry for the answer. I transcribed the wrong code. Correct now:

 foreach (var cc in Model.DdlCentroCusto)
 {
     if (listaCentrosDeCustoEquipe[].CodCentroCusto == cc.Value)
     {
         <option value="@cc.Value" selected="selected">@cc.Text</option>
     }
     else
     {
         <option value="@cc.Value">@cc.Text</option>
     }
 }

This does not work because I did not specify the index of the item, and can be multiple items. I have already seen some code where related to lists, vi tb that for list there is a Contains option (only I need to go in the specific field and pick up the string and it asks for the type of the object), but I do not know which one to use and I do not know how to use.

I do not think it's difficult, so help will be very welcome.

    
asked by anonymous 14.02.2014 / 14:56

3 answers

2
foreach (var itemw in listaCentrosDeCustoEquipe)
 {
     if (itemw.CodCentroCusto == cc.Value)
     {
         <option value="@cc.Value" selected="selected">@cc.Text</option>
     }
     else
     {
         <option value="@cc.Value">@cc.Text</option>
     }
 }
    
14.02.2014 / 14:59
1

I was able to solve my problem:

  @foreach (var cc in Model.DdlCentroCusto)
  {
     if (listaCentrosDeCustoEquipe.Where(x => x.CodCentroCusto.ToString() == cc.Value).Count() > 0)
     {
        <option value="@cc.Value" selected="selected">@cc.Text</option>
     }
     else
     {
         <option value="@cc.Value">@cc.Text</option>
     }
  }

I make a filter in the list so that it is only with values equal to the current item of the foreach, if the list brings more than one result is because this item is in the list and then I mark it in my select.

    
14.02.2014 / 15:14
1
@Html.DropDownList("MeuSelect", listaCentrosDeCustoEquipe.Select(option => new SelectListItem
   {
       Text = option.CodCentroCusto,
       Value = option.CodCentroCusto.ToString(),
       Selected = option.CodCentroCusto == cc.Value)
   }));
    
14.02.2014 / 15:18