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

后端 未结 11 1276
余生分开走
余生分开走 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 03:55

    Using LINQ in one line and with circular search:

    Next of

    YourList.SkipWhile(x => x != NextOfThisValue).Skip(1).DefaultIfEmpty( YourList[0] ).FirstOrDefault();
    

    Previous of

    YourList.TakeWhile(x => x != PrevOfThisValue).DefaultIfEmpty( YourList[YourList.Count-1]).LastOrDefault();
    

    This is a working example (link to the fiddle)

        List fruits = new List {"apple", "banana", "orange", "raspberry", "kiwi"};
        string NextOf = "orange";
        string NextOfIs;
    
        NextOfIs = fruits.SkipWhile(x => x!=NextOf).Skip(1).DefaultIfEmpty(fruits[0]).FirstOrDefault();
        Console.WriteLine("The next of " + NextOf + " is " + NextOfIs);
    
        NextOf = "kiwi";
        NextOfIs = fruits.SkipWhile(x => x!=NextOf).Skip(1).DefaultIfEmpty(fruits[0]).FirstOrDefault();
        Console.WriteLine("The next of " + NextOf + " is " + NextOfIs);
    
        string PrevOf = "orange";
        string PrevOfIs;
    
        PrevOfIs = fruits.TakeWhile(x => x!=PrevOf).DefaultIfEmpty(fruits[fruits.Count-1]).LastOrDefault();
        Console.WriteLine("The prev of " + PrevOf + " is " + PrevOfIs);
    
        PrevOf = "apple";
        PrevOfIs = fruits.TakeWhile(x => x!=PrevOf).DefaultIfEmpty(fruits[fruits.Count-1]).LastOrDefault();
        Console.WriteLine("The prev of " + PrevOf + " is " + PrevOfIs);
    

提交回复
热议问题