简体   繁体   中英

How to make this simple C# code more efficent/elegant

I've three three textBox, textBoxLectura1 , textBoxLectura2 and textBoxLectura3 . When someone clicks on the button button3 I want just to print the entries the user has written.

I made this code and works perfect. I would like to know if there's a more elegant/efficent way to do it without using so many if statements. I would like to maintain the arrayList structure.

    private void button3_Click(object sender, EventArgs e)
    {

        ArrayList myarray2 = new ArrayList();

        if (string.IsNullOrWhiteSpace(textBoxLectura1.Text) == false)
        {
            myarray2.Add(textBoxLectura1.Text);
        }

        if (string.IsNullOrWhiteSpace(textBoxLectura2.Text) == false)
        {
            myarray2.Add(textBoxLectura2.Text);
        }

        if (string.IsNullOrWhiteSpace(textBoxLectura3.Text) == false)
        {
            myarray2.Add(textBoxLectura3.Text);
        }

        if (myarray2.Count > 0)
        {
            foreach (string values in myarray2)
            {
                Console.WriteLine(values );
            }
        }
        else
        {
            MessageBox.Show("no entrys");
        }

    }

The simplest way might be to do something like:

var strings = new List<string>() 
{
    textBoxLectura1.Text,
    textBoxLectura2.Text,
    textBoxLectura3.Text
};

var output = string.Join('\n',strings.Where(s => !string.IsNullOrEmpty(s));
if (!string.IsNullOrEmpty(output)) 
{
    Console.Writeline(output);
}
else
{
    MessageBox.Show("no entrys");
}

A couple of points here. Don't use ArrayList . A typed List<T> is better in pretty much every way. ArrayList is a hold over from C# when it didn't have generics. The only reason to ever use ArrayList is if you are dealing with some legacy (pre 2.0) code that needs it. A List<object> is functional equivalent to an ArrayList , but since a lot of the time you are dealing with homogeneous collections it's much easier to use a List<T> , where T is whatever type you are populating your collection with (in this case string ), and not have to deal with casting every time you try and get something from your collection.

What we do in the code here is we create a List<string> and immediately initialize it with the values of all our textboxes .Text property. It doesn't matter if they are null or empty at the point.

Then we use the really helpful string.Join method. This takes a collection of strings and glues them together with a separator. In this case, we use the newline character ( \\n ). But, since we don't want to include nulls or empty strings ( String.Join would otherwise insert extra newline characters), we use a simple LINQ .Where statement to select only those strings that aren't null or empty.

Here's my take on it.

var notEmpty = new[]  { textBoxLectura1.Text, textBoxLectura2.Text, textBoxLectura3.Text}
    .Where(s => !String.IsNullOrEmpty(s)
    .ToArray();

if (!notEmpty.Any())
{
    MessageBox.Show("No Entries");
    return;
}

Console.WriteLine(string.Join(Environment.NewLine, notEmpty));

I also agree with other posters, ArrayList vs an IEnumerable<T> implementing container is a no-brainer, you should be using a strongly-typed collection type.

You can use a function to Check & Add:.

private void button3_Click(object sender, EventArgs e)
        {

            ArrayList myarray2 = new ArrayList();

            ChecknAdd(textBoxLectura1, myarray2);
            ChecknAdd(textBoxLectura2, myarray2);
            ChecknAdd(textBoxLectura3, myarray2);

            if (myarray2.Count > 0)
            {
                foreach (string values in myarray2)
                {
                    Console.WriteLine(values);
                }
            }
            else
            {
                MessageBox.Show("no entrys");
            }

        }

        void ChecknAdd(TextBox txt, System.Collections.ArrayList Ary)
        {
            if (string.IsNullOrWhiteSpace(txt.Text) == false)
            {
                Ary.Add(txt.Text);
            }
        }

create a procedure like this:

private void addOnArray(ArrayList array, String text) {

    if (string.IsNullOrWhiteSpace(text) == false)
    {
        array.Add(text);
    }

}

And in the caller:

private void button3_Click(object sender, EventArgs e)
{

    ArrayList myarray2 = new ArrayList();
    addOnArray(myarray2, textBoxLectura1.Text);
    addOnArray(myarray2, textBoxLectura2.Text);
    addOnArray(myarray2, textBoxLectura3.Text);

    if (myarray2.Count > 0)
    {
        foreach (string values in myarray2)
        {
            Console.WriteLine(values );
        }
    }
    else
    {
        MessageBox.Show("no entrys");
    }

  }

You can shorten your if(s) to ternary operators... When you add to a List, it'll return the index it was added to, otherwise just assign a -1 to the receiving variable

Then use the same ternary logic to know if you want to print the contents of your ArrayList, or just print "No Entries"

        ArrayList myarray2 = new ArrayList();

        int index = !string.IsNullOrWhiteSpace(textBoxLectura1.Text) ? myarray2.Add(textBoxLectura1.Text) : -1;
        index = !string.IsNullOrWhiteSpace(textBoxLectura2.Text) ? myarray2.Add(textBoxLectura2.Text) : -1;
        index = !string.IsNullOrWhiteSpace(textBoxLectura3.Text) ? myarray2.Add(textBoxLectura3.Text) : -1;

        Console.WriteLine(myarray2.Count > 0 ? string.Join("\n", myarray2.ToArray()) : "No Entries");

I really appreciate the approaches in other answers and the way couple of them have explained why to use Generics vs ArrayLists. This is how I perform it ( learnt it thanks to SO ):

IEnumerable<TextBox> textBoxCollection = this.Controls.OfType<TextBox>();

        foreach (TextBox box in textBoxCollection)
        {
            if (!string.IsNullOrWhiteSpace(box.Text))
            {
                MessageBox.Show(box.Text);   
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM