Get previous/next item of a given item in a List<>

后端 未结 11 1272
余生分开走
余生分开走 2021-02-12 03:18

Says I have this List : 1, 3, 5, 7, 9, 13

For example, given value is : 9, the previous item is 7 and the next item is 13

How can I achieve this using C#?

11条回答
  •  说谎
    说谎 (楼主)
    2021-02-12 04:06

    This can be done using LinkedList

    List intList = new List { 1, 3, 5, 7, 9, 13 };
    
    LinkedList intLinkedList = new LinkedList(intList);
    
    Console.WriteLine("Next Value to 9 "+intLinkedList.Find(9).Next.Value);
    
    Console.WriteLine("Next Value to 9 " +intLinkedList.Find(9).Previous.Value);
    
    //Consider using dictionary for frequent use
    var intDictionary = intLinkedList.ToDictionary(i => i, i => intLinkedList.Find(i));    
    
    Console.WriteLine("Next Value to 9 " + intDictionary[9].Next.Value);
    
    Console.WriteLine("Next Value to 9 " + intDictionary[9].Previous.Value);
    
    Console.Read();
    

提交回复
热议问题