I have a list of ProjectItem class instances: List<ProjectItem> allProjects.
I need to obtain a List<ProjectItemPair> – a list of new class instances, that have ProjectItem projectOne and ProjectItem projectTwo as a properties.
I had to foreach the initial list, and using a bool switch was adding a new ProjectItemPair into a resulting list on every second item in iteration. This is a primitive old school approach. I am sure with Linq I can pair the project instances up effectively. How can I do it?
Well, you could use:
The use of
ElementAtOrDefaultmeans the constructor will be passednullif there’s an odd number of elements.Another somewhat simpler alternative:
This will omit the final element if the input has an odd number of elements, in which case you can do: