Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# how can I access an element in nested array

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading