Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
CSharp /
20180405estring slicingWarning! C#'s csharp> var li = new List<char> {'a', 'b', 'c', 'd', 'e', 'f', 'g'} csharp> li.GetRange(0, 2) { 'a', 'b' } // Seems good, right? csharp> li.GetRange(2, 4) { 'c', 'd', 'e', 'f' } // Ooops! What da hell?
To simulate Python's list slicing, I have this solution: // slice support for lists (like Python) public static List<T> Slice<T>(this List<T> li, int start, int end) { if (start < 0) // support negative indexing { start = li.Count + start; } if (end < 0) // support negative indexing { end = li.Count + end; } if (start > li.Count) // if the start value is too high { start = li.Count; } if (end > li.Count) // if the end value is too high { end = li.Count; } var count = end - start; // calculate count (number of elements) if (count < 0) { count = 0; } return li.GetRange(start, count); // return a shallow copy of li of count elements } For usage examples, here are some tests: [Fact] public void Slice_list() { var li1 = new List<char> {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; Assert.Equal(new List<char> {'c', 'd'}, li1.Slice(2, 4)); Assert.Equal(new List<char> {'b', 'c', 'd', 'e', 'f', 'g'}, li1.Slice(1, li1.Count)); Assert.Equal(new List<char> {'a', 'b', 'c'}, li1.Slice(0, 3)); Assert.Equal(li1, li1.Slice(0, 4).Concat(li1.Slice(4, li1.Count))); Assert.Equal(li1, li1.Slice(0, 100)); Assert.Equal(new List<char>(), li1.Slice(100, 200)); Assert.Equal(new List<char> {'g'}, li1.Slice(-1, li1.Count)); Assert.Equal(new List<char> {'f', 'g'}, li1.Slice(-2, li1.Count)); Assert.Equal(new List<char> {'a', 'b', 'c', 'd', 'e', 'f'}, li1.Slice(0, -1)); Assert.Equal(new List<char> {'c', 'd', 'e'}, li1.Slice(2, -2)); } See the current version here. |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |