How do you get the index of a number in a linked list?

后端 未结 5 360
天命终不由人
天命终不由人 2021-01-14 01:50

I have a linked list constructed as follows:

LinkedList linked = new LinkedList();
var array = new int[] { 23, 55, 64, 65 };
foreach (         


        
5条回答
  •  情话喂你
    2021-01-14 02:42

    Here is an alternate LINQ implementation that avoids creating anonymous objects and returns -1 if the item is not in the list:

    int index = linked.Select((n, i) => n == 64 ? (int?)i : null).
                FirstOrDefault(n => n != null) ?? -1;
    

    It converts the sequence of numbers to a sequence containing the index of a match or null otherwise. It takes the first of these if there is one, otherwise converts the default int? to -1.

    Edit:

    Here is a better (simpler and more performant) alternative:

    int i = linked.TakeWhile(n => n != 64).Count();
    

    i will either be equal to the index, or equal to linked.Count if the value 64 was not found.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题