How to verify if there is a specific value (string) in a list in C#?

Asked

Viewed 1,154 times

4

I am trying to mount a select Multiple input and leave marked 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 more or less this: (Notice I’m using Razor)

Sorry who already answered. I transcribed the wrong code. I fixed it 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 may be several items. I’ve seen some Where code related to lists, I’ve also seen that for the list there is a Contains option (only I need to go in the specific field and pick by the string and it asks the type of the object), but I don’t know which one to use and I don’t know how to use.

I believe that it is not difficult so a help will be very welcome.

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

1

I managed 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 only has values equal to the current foreach item, if the list brings more than one result is because this item is in the list and then I mark it in my select.

  • 2

    Do not use Where why it will iterate the entire list. Use Any(). Ex: listCentrosDeCustoEquipe.Any(x => x.CentroCusto.Tostring() == cc.Value)

  • Great tip. In this case the list will have a maximum of 5 items but I will use!

1

@Html.DropDownList("MeuSelect", listaCentrosDeCustoEquipe.Select(option => new SelectListItem
   {
       Text = option.CodCentroCusto,
       Value = option.CodCentroCusto.ToString(),
       Selected = option.CodCentroCusto == cc.Value)
   }));
  • 1

    I won’t test because mine is already working, but it seems a great solution. + 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.