2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用以下方法過濾在進(jìn)行平均之前未輸入的結(jié)果Where:
private void calculate_btn_Click(object sender, EventArgs e)
{
var d1 = TimeSpan.Parse(textBox1.Text);
var d2 = TimeSpan.Parse(textBox2.Text);
var d3 = TimeSpan.Parse(textBox3.Text);
var sourceList = new List<TimeSpan> {d1,d2,d3};
var averageTicks = sourceList.Where(t=>t.Ticks>0).Average(t=>t.Ticks);
var averageTimeSpan = new TimeSpan(averageTicks);
averagelabletext.Text = averageTimeSpan.ToString();
}
我可能會(huì)做更像這樣的事情(為了清楚起見):
private void calculate_btn_Click(object sender, EventArgs e)
{
var textboxes = new List<TextBox> {textBox1, textBox2, textBox3};
var ticks = textboxes.Select(t=>TimeSpan.Parse(t.Text).Ticks);
var enteredTicks = ticks.Where(t=>t!=0);
var averageTicks = enteredTicks.Average();
var averageTimeSpan = new TimeSpan(averageTicks);
averagelabletext.Text = averageTimeSpan.ToString();
}
然后進(jìn)一步簡化:
private void calculate_btn_Click(object sender, EventArgs e)
{
var textboxes = new List<TextBox> {textBox1, textBox2, textBox3};
var ticks = textboxes
.Select(t=>TimeSpan.Parse(t.Text).Ticks)
.Where(t=>t!=0);
.Average();
var averageTimeSpan = new TimeSpan(ticks);
averagelabletext.Text = averageTimeSpan.ToString();
}

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試使用 TryParse。如果它仍然以解析空字符串結(jié)束,請?zhí)砑右粋€(gè)檢查!string.IsNullOrWhiteSpace(TextBox1.Text) && TimeSpan.TryParse...
private void calculate_btn_Click(object sender, EventArgs e)
{
var sourceList = new List<TimeSpan>();
TimeSpan timeSpan;
if (TimeSpan.TryParse(textBox1.Text, out timeSpan)) {
sourceList.Add(timeSpan);
}
if (TimeSpan.TryParse(textBox2.Text, out timeSpan)) {
sourceList.Add(timeSpan);
}
if (TimeSpan.TryParse(textBox3.Text, out timeSpan)) {
sourceList.Add(timeSpan);
}
var averageTimeSpan = new TimeSpan(Convert.ToInt64(sourceList.Average(x => x.Ticks)));
averagelabletext.Text = averageTimeSpan.ToString();
}
- 2 回答
- 0 關(guān)注
- 190 瀏覽
添加回答
舉報(bào)