【发布时间】:2017-01-01 21:18:24
【问题描述】:
我正在寻找一种在列表视图中搜索精确值或列表中最接近它的值的方法。
这些值都是时间值(“HH:mm:ss”)。我还没有写很多代码,但我会发布我目前所写的。
以下方法引用了一个名为 lstData 的 ListView,它保存了时间值。索引被传递给选择特定时间的方法。 我想要做的是在 lstData 中的这个位置取值,并在另一个名为 lstReport 的 ListView 中找到相同的值或最接近的值。 lst Report 不一定有相同的时间值,但有很多类似的,格式相同,因此我希望选择 lstReport 中最接近的值。
private void SelectTime(int val)
{
try
{
CurrentIndex = val;
lstData.Items[CurrentIndex].Selected = true;
lstData.EnsureVisible(CurrentIndex);
String text = lstData.Items[CurrentIndex].Text;
MessageBox.Show("Time Selected: " + text);
// This is where I want to search lstReport for the closest time value
// to lstData.Items[CurrentIndex] value
this.Refresh();
}
catch
{
}
}
如果我没有很好地解释这一点,我深表歉意,如果是这种情况,请发表评论,我会尽量让它更清楚。谢谢
编辑
// get the selected item from lstData
String text = lstData.Items[CurrentIndex].Text;
// parse the value
long SelectedDate = DateTime.Parse(text).Ticks;
// extract the listview items into a list of strings
List<string> list = lstData.Items.Cast<ListViewItem>().Select(item => item.Text).ToList();
//By converting the values to Long, we can get the closest value using Math.Abs.
string closest = list.Aggregate((x, y) => Math.Abs(DateTime.Parse(x).Ticks - SelectedDate) < Math.Abs(DateTime.Parse(y).Ticks - SelectedDate) ? x : y);
【问题讨论】:
-
对于第二个列表的每个项目,减去日期项目,得到 timeSpan 的 totalSeconds,执行 Math.Abs() 并保持最低结果可能会成功
标签: c# list listview arraylist listviewitem