C# Select IEnumerable of matching elements including and excluding end points

C# Select IEnumerable of matching elements including and excluding end points

I wanted to be able to select sequential elements from a list based on a specified predicate. I needed to be able to include or exclude the begin and end elements as well. Here is how I made use of Linqs skipWhile and takeWhile extensions to do this:

Selecting matching elements, including the start and end points:


var matchingObjects = container.ListObjects()
.SkipWhile(s => !s.Key.Equals(startingObject.Key))
.TakeWhile(s => !s.Key.Equals(endingObject.Key))
.ToList();

//now find the end point and include it
matchingObjects.AddRange(container.ListObjects()
.SkipWhile(s => !s.Key.Equals(endingObject.Key)).Take(1)
.ToList());

return matchingObjects;

Selecting matching elements, not including the start and end points:

container.ListObjects()
.SkipWhile(s => !s.Key.Equals(startingObject.Key)).Skip(1)
.TakeWhile(s => !s.Key.Equals(endingObject.Key)).ToList();

I was having some trouble achieving the including end points version with one line, so I resorted to adding the last item as a separate call. I am sure there is a more elegant way to do this, so any feedback there is welcome from you Linq gurus 🙂

thanks,

Brent

Share Your Thoughts!

Testimonials

What My Clients Say

Karin - Hope and Future

Brent has always been very prompt and generally exceeds our expectations with his work. His maintenance fee is very reasonable. I strongly recommend him!  We get many compliments on our beautiful web site!

Dan

I contacted Krueger Web Design and Brent did everything.  He setup a test site with the changes so we could verify everything was correct before we transferred from my old hosting provider.  During the setup and conversion Brent was extremely professional and responsive. He responded to any issues the same day.

Dan Kaufman
Emily - GFCLT

We've had a great experience working with Krueger Web Design. Prompt responses, great ideas, effective work... all at a reasonable price! This was the perfect fit for our organization.

Mahmud - ACMC

I would love to recommend you to anyone! You have been very helpful when we needed you the most.

Brian - SEMNIC

Working with Krueger Web Design was effortless. Communicating what I wanted for the website and the results that I saw were identical. The customer service was always prompt and I am completely satisfied with the product.

Zach - Stadium Club

Exactly what I wanted! Fast turnaround time and very affordable. Answered all of our questions quickly and made adjustments promptly. Very easy to work with and puts everything into terminology that even I can understand!

Contact Krueger Web Design

Have a question for me? Need an estimate on some work? You can email me at brent@kruegerwebdesign.com or drop me a line using the button below:

Copyright © 2017 Krueger Web Design - All rights reserved
Web Design in Madison, WI