我正在寻找一种方法来通过 ListView 搜索列表中的精确值或最接近的值。
这些值都是时间值(“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);
最佳答案
您可以使用 LINQ 通过对时间的绝对差进行排序来获取最接近的值。假设您有两个 DateTime
类型的列表 lstReport
和 lstData
。然后这样做
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);
//Get the closest DateTime to the Current item of lstData
DateTime MinimumDifferenceItem = lstReport.Items.Cast<DateTime>().OrderBy(Dt => Math.Abs((Dt - (DateTime)lstData.Items[CurrentIndex]).Milliseconds)).First();
this.Refresh();
}
catch { }
}
别忘了添加
using System.Linq;
到您的文件。
编辑:
如果您的列表仅包含字符串,您可以通过添加 Convert.ToDateTime
来修改查询,例如
String MinimumDifferenceItem = lstReport.Items.Cast<string>().OrderBy(Ts => Math.Abs((Convert.ToDateTime(Ts) - Convert.ToDateTime(lstData.Items[CurrentIndex])).Milliseconds)).First();
关于C# ListView - 搜索准确的时间值 (HH :mm:ss) or closest value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145313/