Search code examples
c#arraystextboxsubstringchecklistbox

Is it possible to use substring with OfType<string>?


I'm in a school project and I was wondering how show in a multiline textBox - not a listBox, that was part of the question - how to show the first five letters of checked items of a checkedListBox. We can't show them directly, we have to create an array that will be saved in a User class by using the constructor. My first thought was to use selectedIndexChanged event of the checkListBox and use an incremented, .Items and .substring to put the substring selected into an array. Here is my first code:

private void checkedListBox_programmes_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selection = checkedListBox_programmes.SelectedIndex;

        if (selection != -1)
        {
            if (indice < 5)
            {
                tabProgrammes[indice] = checkedListBox_programmes.Items[selection].ToString().Substring(0, 6);
                indice++;
            }
            else
            {
                MessageBox.Show("Tableau de données est rempli");
            }
        }
    }
}

*tabProgrammes and indice are initialise in my partial class

That didn't worked because unchecking index would add a string in my array. So, second code (I use a buton_click event):

// remplissage du tableau avec les éléments sélectionnées
tabProgrammes = checkedListBox_programmes.CheckedItems.OfType<string>().ToArray();

// création du profile
Profil unProfil = new Profil(textBox_Prenom.Text, textBox_Nom.Text, textBox_Utilisateur.Text, dateTimePicker_Naissance.Value, tabProgrammes);

// affichage des donnees
textBox_Affichaqe.Text = unProfil.ToString();

That work super well because I can check and uncheck without problems. SO, my problem is that I need to put in my array only the substring(0,6) of my checked items. An idea?


Solution

  • Yes, you can use Substring() on the result of OfType<string>().

    To do so, you need to use the Linq Select() operator in your specific case.

    Here is an example:

    static void Main(string[] args)
    {
        var dataSource = new object[]
        {
            42,
            "bonjour",
            "allo",
            1000,
            "salut"
        };
    
        var myStrings = dataSource
            .OfType<string>()
            // In this case, we use substring only if the length of the string is above 6.
            .Select(s => s.Length > 6 ? s.Substring(0, 6) : s)
            .ToArray();
    
        foreach (var item in myStrings)
        {
            Debug.WriteLine(item);
        }
    }
    

    It outputs the following:

    bonjou
    allo
    salut