课程: C# Practice: Generic Collections
Solution: Use a slice to get a subset
- [Instructor] In this code challenge, we're looking for a way to get a slice of data or a subset of data from a source and it's supposed to be a contiguous set of information, so all the items are next to each other in the source. I ask you to do this with two sources, an array and a list of t. For the first example, we're looking at the array example, so here I've got this GetSlicesFromArray and the plan is to return a string array, and then the source is a string array. And one of the ways you can work with an array, of course, is to use an index value to find one of the items. In the newer versions of C-sharp, there's this range operator that's lets us specify a range of values, so I'm starting at 3 and I'm going up to, but not including 6, so they'll only get me items 3, 4, and 5. I like the syntax, I think this is a really elegant syntax that they added recently in C-sharp. So what I'm doing next is I'm doing it again over here, I'm getting all items, 8 through 11 or 8, 9 and 10, and then I'm concatenating the two items together and then I'm calling ToArray to make sure it's turned back into a string array and then I return that value, and as you can see over here, I'm getting the results that I'm looking for. What about working with a list of string? You can't use this syntax in a list, so we have to find another way, so there's the old school way of doing it, prelink, which is called GetRange and then there's the link version, so let's look at both of those. So there's GetRange, which is a method on the list of t, so I call GetRange, I say start at position 3 and get three items and then I do that a second time, start at 8 and get three items, and then I am taking the original lists and I'm adding a range, the value that I got here, so that's one way of getting the results. The other way is to use link and in link you can use the Skip and the Take, so I skip the first three items, then I take 3 and then I skip 2 and 8 and take 3, and then of course I call Concat again to put these two together and then of course I would call return q to turn this into a list, I didn't run that code, I ran the first example where I used the range and that's what you're seeing, here.