Home > Mobile >  C# how can I access an element in nested array
C# how can I access an element in nested array

Time:09-26

Type of the array

ReplyKeyboardMarkup replyKeyboardMarkup = new(new[]
                {
                 new KeyboardButton[]{ "January", "February", "March", "April"},
                 new KeyboardButton[]{ "May", "June", "July", "August"},
                 new KeyboardButton[]{ "September", "October", "November", "December"},
                })

I have the following code, where ReplyKeyboardMarkup is a custom class from telegram.Bot api from nuget packages. How can I access a specified element, like first string in first KeyboardButton array (January)?

CodePudding user response:

You are looking for the Keyboard property:

string january = replyKeyboardMarkup.Keyboard
        .FirstOrDefault()?.FirstOrDefault()?.Text;

The Text property comes from the KeyboardButton and is what you have specified.

You have commented that you want to access it as a real array, because you want to modify each button easily. Then you can use this approach:

KeyboardButton[][] kbButtonArray = replyKeyboardMarkup.Keyboard as KeyboardButton[][]
            ?? replyKeyboardMarkup.Keyboard.Select(x => x.ToArray()).ToArray();    

Actually the try-cast already works in the current implementation, so no need for the LINQ query. But since it it's an IEnumerable<IEnumerable<KeyboardButton>> that cast might fail in future.

  • Related