将重复的foreach循环转换为方法,使其仅重复一次

时间:2016-04-26 10:54:32

标签: c# methods foreach

所以,我的问题可能会变得简单。我知道如何创建一个从应用程序回调的方法,但我的问题是试图弄清楚如何以这种方式正确地做到这一点。我需要采取重复的foreach循环:( foreach(事件中的票证)             {                 if(t.getName()。Equals(cbEvents.SelectedItem.ToString()))                 { )  并将其更改为在代码中调用两次的方法。请帮忙。代码如下。

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TicketPurchasing
{
public partial class Form1 : Form
{
    private ArrayList events;

    public Form1()
    {
        InitializeComponent();
        events = new ArrayList();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //Create events
        events.Add(new Game(12.00, "KSU vs UGA", "Convocation Building",   "bball", "Basketball"));
        events.Add(new Game(15.00, "KSU vs GSU", "Stadium", "fball", "Football"));
        events.Add(new Concert(8.00, "Country Music", "Campus Green", "hayes", "Hunter Hayes"));
        events.Add(new Concert(12.00, "Rock/Pop", "Campus Green", "m5", "Maroon5"));

        //Load combobox
        foreach (Ticket t in events)
        {
            cbEvents.Items.Add(t.getName());
        }
    }

    private void btnDetails_Click(object sender, EventArgs e)
    {
        //Get name of selected item from combobox
        string eventName;

        //Traverse array to determine the match
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                //Display details
                lblDetails.Text = t.getDetails();

                //Display image
                displayImage(t.getFileName());
            }
        }
    }

    private void displayImage(string file)
    {
        Size size = new Size(173, 180);
        Image img = (Image)Properties.Resources.ResourceManager.GetObject(file);
        img = (Image)(new Bitmap(img, size));
        pbImage.Image = img;
        pbImage.Refresh();
        pbImage.Visible = true;
    }

    private void txtTickets_TextChanged(object sender, EventArgs e)
    {
        //Get number of tickets

        int num = int.Parse(txtTickets.Text);

        double ticketCost = 0;

        //Get cost of ticket
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                ticketCost = t.getCost();
            }
        }

        //Calculate cost
        double total = num * ticketCost;

        //Display cost
        txtCost.Text = total.ToString("c");
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        //Exit the application
        this.Close();
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        //Clear all information
        lblDetails.Text = "";
        pbImage.Image = null;
        txtTickets.Text = "0";
        txtCost.Text = "";
    }

}
}

2 个答案:

答案 0 :(得分:0)

你想要达到这样的目标吗?

    private void btnDetails_Click(object sender, EventArgs e)
    {
        //Get name of selected item from combobox
        string eventName;

        //Traverse array to determine the match
        MethodAfterRefactor(() => 
        {
            //Display details
            lblDetails.Text = t.getDetails();

            //Display image
            displayImage(t.getFileName());
        });
    }

    private void MethodAfterRefactor(Func<object> p)
    {
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                p.Invoke();
            }
        }
    }

答案 1 :(得分:0)

尝试稍微区别一点,让我们从你想要做的事情开始。

您有两个列表,一个代表View artefacts cbEvents,另一个代表背后的数据(有时称为ViewModel)events

您要做的是与View中的ViewModel匹配,因为将名称放入视图中。

如果您将ViewModel放入View中,以便可以将其呈现为名称,那么此代码就会消失。像

这样的东西
public class Ticket
{
    ...

   public string override ToString() { return getName(); }
}

private void Form1_Load(object sender, EventArgs e)
{
     ...
     //Load combobox
    foreach (Ticket t in events)
    {
        cbEvents.Items.Add(t);
    }
}

然后你可以做像

这样的事情
private void btnDetails_Click(object sender, EventArgs e)
{        
    Ticket t = cbEvents.SelectedItem as Ticket;
    if (t !=null)
    {
            //Display details
            lblDetails.Text = t.getDetails();

            //Display image
            displayImage(t.getFileName());            
    }
}

这显然是一种完全不同的思考方式但更容易。您可能还会发现某些控件不支持很好地绑定到对象,在这种情况下(至少在WinForms中)您可以使用Tag字段

 lblText.Text = t.getName();
 lblText.Tag = t;

或在WPF中DataContext,然后绑定到字段,例如

<TextBlock Text="{Binding Name}"/>