需要查找给定键是否存在于可用键范围内并返回相应的索引值



我有大量的迭代计数数据,对应的时间以秒为单位。基于任何输入秒需要使用 C# 确定该输入秒属于哪个特定迭代计数。

可用数据:

string----int
iter_1----00
iter_2----06
iter_3----08
iter_5----20
.
iter_n----n

期望的输出

03(input)-iter_1(output),
12(input)-iter_3(output)......
输入可以大到1000,

代码需要根据输入秒数获得所需的输出1000-10000次。

我相信这可以使用列表/字典来完成。我不确定执行时间。任何数据结构都可以。

我使用了LIST并使用线性搜索来解决这个问题。由于用于填充列表的数据已排序。我没有使用排序列表.在将列表用于 1500 个项目时没有发现任何显着的时间性能问题,并进行了 30000 次的线性搜索。

class Program
{
    //Class to store iteration value and time
    class test
    {
        public String Cycle;
        public int Time;
    };
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("test.xml");            
        List<test> Check = new List<test>();
        foreach (XmlNode node in doc.DocumentElement.ChildNodes)
        {
            // Deatils to fill the list are obtained via XML , which is already sorted.               
            int totsec = (int)TimeSpan.Parse(node.Attributes["ElapsedTime"].Value).TotalSeconds;
            Check.Add(new test() { Cycle = node.Name, Time = totsec });              
        }
        // to Find the iteration , Do linear search via Find Function
        int inputtocheck = 130;
        int index = Check.IndexOf(Check.Find(item => item.Time >= inputtocheck ));
        Console.WriteLine(Check[index].Cycle);
    }
}

最新更新