- Home /
Get Dropdown Index value based on text value using Where c# filter
Hi all,
I'm trying to set the default selection for a Dropdown based on the text value, using the Where filter function in C#, but I cant get this to work.
For example, a dropdown that's populated like: [0] "Item 1", [1] "Item 2", [2] "Item 3", [3] "Item 4", [4] "Item 5"
Using some code like this:
int defaultDropDownIndex = myDropDown.options.Where(i => (myDropDown.OptionData == "Item 4"));
This issue is the condition statement (myDropDown.OptionData == "Item 4") I couldn't find anyway to get the dropdown values.
Is it even possible to use the Where filter for this?
Any help would be much appreciated. Thanks
Simple tutorial to get value https://www.youtube.com/watch?v=FteXwEdED0Y&t=2s and get dropdown text https://www.youtube.com/watch?v=0hPzm91nhGU&t=
Answer by fafase · Mar 19, 2018 at 11:52 AM
Where method will not return an integer but an OptionData object. So you're up to no good there.
What you need is FindIndex:
int index = myDropDown.options.FindIndex((i) => { return i.text.Equals("Item 4"); });
Here is a quick implementation of what is likely to happen in there with extension method:
public static int GetIndexByName(this Dropdown dropDown, string name)
{
if (dropDown == null) { return -1; } // or exception
if(string.IsNullOrEmpty(name) == true) { return -1; }
List<Dropdown.OptionData> list = dropDown.options;
for (int i = 0; i < list.Count; i++)
{
if (list[i].text.Equals(name)) { return i; }
}
return -1;
}
Hi fafase.
That worked a treat! I could have done with a custom function but I prefer the elegant way :)
Thanks very much!