Good day! There is an array of List<Button> . Can you please tell me how to get the button11 element button11 from an array by its name? Apparently, you need to use the List<T>.FindIndex - метод (Predicate<T>) , but I can't figure it out.
- oneworth seeing help on this method - Grundy
- @Grundy, it was there that I looked) I’m learning Java, but I began to learn Unity, so some things are difficult. The syntax is sometimes very different. - Pollux
- So there is just an example of use - Grundy
|
2 answers
The FindIndex() method takes a delegate of type Predicate<T> as a parameter. This means that it accepts methods that have one parameter of type T and that return a bool value. Since your list contains buttons, your method will look like this:
private string _buttonName; ... private bool IsButtonFound(Button button) { return button.Name == _buttonName; } And you need to use it like this:
_buttonName = "..."; int index = list.FindIndex(IsButtonFound); If you use anonymous methods , you can do without the _buttonName field:
int index = list.FindIndex(b => b.Name == "..."); If you need an index in order to get this button later, you can immediately try to get it using the FirstOrDefault() extension method:
using System.Linq; ... var button = list.FirstOrDefault(b => b.Name == "..."); if (button != null) { // кнопка найдена } |
Isn't it easier to do this:
Button btn = btn_list.First(n => n.Name == "button11"); // btn_list - ваш List<Button> |