How to select an item and the previous from an IEnumerable<>?

Viewed 103

I would like to know if it is possible to select from an IEnumerable a value and the value just before.

For ex :

IEnumerable<string>  my_Enu

Which is a collection of items ("A","B","C","D","E") for ex.

I would like to create a second IEnumerable :

IEnumerable<string> test_Enu = my_Enu.Where(item => item =="C")

And I would like to add too the previous item which is "B".

Could you please tell me if there is a way to do it?

Thank you in advance for your help.

1 Answers

I think you can use simple LinkedList.

IEnumerable<string> collection = new string[] { "A", "B", "C" };
var linkedList = new LinkedList<string>(collection);
var element = linkedList.Find("C");
var result = new[] { element, element.Previous };

And of course you would need to add null-checks

Related