有条件的缩短代码添加字典

时间:2018-12-04 09:57:02

标签: c# winforms

我有此代码:

Dictionary<string, string> items = new Dictionary<string, string>();
if(TextBox1.Text != "")
{
    items.Add(TextBox1.Name, TextBox1.Text);
}
if (TextBox2.Text != "")
{
    items.Add(TextBox2.Name, TextBox2.Text);
}
if (TextBox3.Text != "")
{
    items.Add(TextBox3.Name, TextBox3.Text);
}

它工作正常,但是大约有20 TextBox个项目,我想减少冗余。有什么办法可以缩短时间?

4 个答案:

答案 0 :(得分:5)

您可以将TextBoxes添加到集合中,然后使用LINQ:

TextBox[] allTxt = {TextBox1,TextBox12,TextBox3,...};

Dictionary<string, string> items = allTxt
    .Where(txt => !string.IsNullOrEmpty(txt.Text))
    .ToDictionary(txt => txt.Name, txt => txt.Text);

答案 1 :(得分:2)

您可以使用Controls表单集合,并使用OfType方法根据控件的类型将其过滤掉,然后将其转换为字典:

var tbs = this.Controls.OfType<TextBox>()
    .Where(tb => ! string.IsNullOrEmpty(tb.Text))
    .ToDictionary(tb => tb.Name, tb => tb.Text);

答案 2 :(得分:1)

您可以使用包含所有文本框的数组,并使用private void CreateGraph() { float[] yDataL = {30, 60, 500,231}; String[] xDataL = {"Jan", "Feb" , "Mac" , "Apr"}; LineChart lineChart = (LineChart) findViewById(R.id.chart); ArrayList<Entry> yEntrys = new ArrayList<>(); final ArrayList<String> xEntrys = new ArrayList<>(); for(int i = 0; i < yData.length; i++){ yEntrys.add(new Entry(i, yData[i])); } for(int i = 1; i < xData.length; i++){ xEntrys.add(xData[i]); } LineDataSet dataSet = new LineDataSet(yEntrys, ""); dataSet.setColor(Color.parseColor("#7500ca")); dataSet.setCircleColor(Color.parseColor("#7500ca")); dataSet.setLineWidth(1f); dataSet.setCircleRadius(5f); dataSet.setDrawCircleHole(false); dataSet.setDrawValues(false); XAxis xAxis = lineChart.getXAxis(); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setGranularity(1f); xAxis.setGranularityEnabled(true); xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return xEntrys.get((int) value % xEntrys.size()); } }); YAxis rightAxis = lineChart.getAxisRight(); rightAxis.setEnabled(false); LineData pieData = new LineData(dataSet); lineChart.getXAxis().setDrawGridLines(false); lineChart.getAxisLeft().setDrawGridLines(false); lineChart.getAxisRight().setDrawGridLines(false); lineChart.getAxisLeft().setDrawAxisLine(false); lineChart.getAxisRight().setDrawAxisLine(false); lineChart.getAxisLeft().setDrawLabels(false); lineChart.getAxisRight().setDrawLabels(false); lineChart.getLegend().setEnabled(false); lineChart.setDescription(null); lineChart.setData(pieData); lineChart.invalidate(); } Where

ToDictionary

答案 3 :(得分:-1)

为此创建一个函数。

import serial
import libevdev
def serialHandler():
    ser = serial.Serial(
        port = '/dev/ttyS0',
        baudrate = 115200,
        parity = serial.PARITY_NONE,
        stopbits = serial.STOPBITS_ONE,
        bytesize = serial.EIGHTBITS,
        timeout = 0
    )

    fd = open ('/dev/input/event0', 'rb')
    d = libevdev.Device(fd)
    if not d.has(libevdev.EV_ABS.ABS_X):
        print('This is not your touch device.')
        sys.exit(0)
    while True:

        for e in d.events():
            if e.matches(libevdev.EV_ABS):
                if e.matches(libevdev.EV_ABS.ABS_X):
                    ser.write(bytes("ABSOLUTE X {}\n".format(e.value),encoding='utf-8'))
                    #x = e.value

                if e.matches(libevdev.EV_ABS.ABS_Y):
                    ser.write(bytes("ABSOLUTE Y {}\n".format(e.value),encoding='utf-8'))
                    #y = e.value

                #return x, y
#anotherFunc(serialHandler())

在您的主要功能中,只需像上面这样调用此功能

public function test(TextBox text)
{
    if(text.Text != "")
    {
        items.Add(text.Name, text.Text);
    }
}