Coolthing Of Theday

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 4 December 2013

Slicing .NET - NSlice, the Python like Slice for .Net

Posted on 17:31 by Unknown

Works on my machine - Slicing for .NET

...

First odd thing I read about Python was that a developer can use negative array indices. My reaction was: Why would I even want to get an IndexOutOfRangeException? That is just silly. But then I read what they actually do. They are just like the normal ones. The only difference is that they index the array backwards, for example: -1 means last, -2 means one before last, and so on. That is really handy. I cannot remember how many times I wrote count-1 or count-i.

After that I discovered that Python has an even cooler feature called array slicing. It is something like a quick for loop version. Let me show you an example:

array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print array[1:9:2]

The above code prints [1,3,5,7].

So formally speaking slicing has the following form (each argument can be negative, all arguments are optional):

[ start_index : exclusive_boundary : iteration_step ]

...

This is a really powerful though succinct syntax. Look at the following two examples:

array[::-1] #reverses the array array[1:-1] #skips first and last element

Then I stared to think about those features - how can I port them to C# ?

NSlice

I decided to give it a try and created a .NET library. At the moment there are 3 extension methods:

- Slice – performs slice on a passed collection.
- At - works like an ElementAt extension. The only difference is that the index argument passed to an At extension can be negative.
- AtOrDefault - works like an ElementAtOrDefault extension, but it also accepts negative indices.

But there is more into it. NSlice was written to allow slicing 3 types of .NET collections in the most efficient manner:

- Indexed collections (IList<> implementations) - slicing is performed eagerly and instantly. It does not matter whether the collection has 10 elements or 10 million elements. This is because the result is not created by copying elements, but by creating a transparent view over source collection.
- Enumerables (IEnumerable<> implementations) - slicing is performed lazily. Each possible slice scenario was implemented separately to achieve the best speed performance and least memory footprint. It fits nicely into the LINQ model and could be even used to slice a stream, if the latter was wrapped into IEnumerable<> implementation.
- Strings - slicing is performed eagerly and a new string is returned as a result.

nabuk / NSlice

About NSlice

NSlice is a free .NET library, designed to give you more flexibility in manipulating collections, originally inspired by Python slicing feature.

(Jump straight to the Cheat Sheet if you want to see code samples right away.)

Overview

NSlice was written to allow slicing 3 types of .NET collections in the most efficient manner:

  • Indexed collections (IList<> implementations) - slicing is performed eagerly and instantly. It does not matter whether the collection has 10 elements or 10 million elements. This is because the result is not created by copying elements, but by creating a transparent view over source collection.
  • Enumerables (IEnumerable<> implementations) - slicing is performed lazily. Each possible slice scenario was implemented separately to achieve the best speed performance and least memory footprint.
    It fits nicely into the LINQ model and could be even used to slice a stream, if the latter was wrapped into IEnumerable<> implementation.
  • Strings - slicing is performed eagerly and a new string is returned as a result.

What is slicing ?

Slicing is just a for loop shortcut. Look at the following example:

...

But there is more. Slice allows each argument to be negative. It might seem weird to use negative indices but they are really useful. What are negative indices? They just index the collection backwards, for example: -1 means last, -2 means one before last and so on. See the following two examples to grasp the idea:

  • Get last five elements: Slice(-5)

  • Get collection without first and last element: Slice(1, -1)

...

nabuk / NSlice - Cheat Sheet

This page contains short code snippets that demonstrate NSlice features. If not specified explicitly, examples assume that collection variable has previously been initialized like this:

image

Like the author, the thought of a negative index seems really weird, but after reading about NSlice, it kind of makes sense. And it's much cooler than a reverse for loop. Then there's the other features too...Oh and that he's released the source. Cool, cool and double cool...

Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in .Net, C#, Development | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Mr. 7,000! This is my 7,000th post...
    Before this post; After; 20 visits between taking these snaps? Oh wait, that's probably me searching for past related posts....
  • "Windows Server Essentials Media Pack" (DNLA Stream, HTML5 and Dashboard Media stuff)
    Microsoft Downloads - Windows Server Essentials Media Pack This pack enables the media streaming functionality for Windows Server 2012...
  • Rad Gate Post... Get your Red Gate Post here...
    simple talk - Melanie Townsend - Get a copy of the Red Gate Post We recently put together a newspaper of some of the best articles fr...
  • Windows Management Framework 4.0 (PowerShell 4, PowerShell ISE, Management OData, WMI, etc.) now available
    Keith Hill's Blog - PowerShell 4.0 Now Available You can get PowerShell 4.0 for down level operating systems now via the WMF 4.0 d...
  • Viasfora - Your new favorite Visual Studio Text/*ML Editing Extension?
    Winterdom - Introducing Viasfora A couple of days ago, I unveiled Viasfora , my latest attempt at building a decently packaged extensi...
  • "Windows Server [2012 R2]: The Best Infrastructure to Run Linux Workloads"
    In the Cloud - What’s New in 2012 R2: Enabling Open Source Software Part 4 of a 9-part series . ... There are a lot of great s...
  • [Hardware Review] Life with Haswell... Haswell/Harris Beach Intel SDS Ultrabook Review - Part 2
    "So Greg, how's life with Haswell been?" "Pretty Sweet! (Mostly)" I've been given an opportunity to review t...
  • Fuzzy Lookup Add-In for Excel (Insert lame "Fuzzy, wuzzy was an Excel..." snip here)
    Microsoft Downloads - Fuzzy Lookup Add-In for Excel The Fuzzy Lookup Add-In for Excel performs fuzzy matching of textual data in Exce...
  • Caliburn.Micro v1.5.0 released (CM gets Tasks, Async/Await and Share/Setting for RT... and bug fixes of course)
    Caliburn.Micro - Caliburn.Micro v1.5.0 "Release Notes This release fixes many bugs. It also adds support for Task and async/a...
  • Just about everything you ever wanted to know about SQL Server Date and Time Data Types...
    CodeProject - Date and Time Data Types and Functions - SQL Server (2000, 2005, 2008, 2008 R2, 2012) Introduction It would be bette...

Categories

  • .Net
  • 3DPrinting
  • AFeedYouShouldRead
  • Agile
  • ALM
  • Amazon
  • Amiga
  • Analytics
  • Android
  • ASP.NET
  • Azure
  • BigData
  • bing
  • Blogging
  • Book
  • BookReview
  • BUILD
  • C
  • C#
  • C++
  • Career
  • Cat
  • cheatsheet
  • ClickOnce
  • Cloud
  • ComputerHardware
  • css
  • Data
  • DBA
  • DependencyInjection
  • Deployment
  • Design
  • Development
  • devops
  • DVCS
  • ebook
  • EDD
  • Education
  • EnterpriseLibrary
  • EntityFramework
  • Exchange
  • Expression
  • gadget
  • Game
  • GIT
  • Google
  • Government
  • Hadoop
  • hardware
  • HardwareReview
  • HaswellReview
  • HTML5
  • Humor
  • IE
  • IEExtension
  • IfAllElseFails
  • IIS
  • ILMerge
  • Image
  • Infographic
  • interview
  • InversionOfControl
  • Java
  • Javascript
  • Kinect
  • LightSwitch
  • LINQ
  • Linux
  • LosAngeles
  • Lucene
  • Lync
  • MEF
  • Metro
  • MicrosoftOffice
  • MicrosoftOutlook
  • Mono
  • MVC
  • MVVM
  • NetMon
  • NLP
  • NoSQL
  • NuGet
  • OData
  • OneNote
  • OpenXML
  • Paint.Net
  • Personal
  • Photosynth
  • Physics
  • portable
  • Poster
  • PowerShell
  • Preparedness
  • Presentation
  • Prism
  • PrivateCloud
  • RegEx
  • RemoteDesktop
  • Reporting
  • RIAServices
  • Science
  • ScienceFiction
  • Scratch
  • Scrum
  • ServiceBus
  • SharePoint
  • Silverlight
  • SimiValley
  • SPA
  • Space
  • SQLServer
  • Storyboard
  • Surface
  • SVG
  • SystemAdministration
  • T4
  • TeamBuild
  • TeamFoundationServer
  • TechEd
  • Training
  • TypeScript
  • UnitTesting
  • UnityApplicationBlock
  • Utility
  • Veteran
  • VirtualMachine
  • Visio
  • VisualBasic
  • VisualStudio
  • WCF
  • Web X.X
  • Webcast
  • WebFeed
  • WebMatrix
  • Windows
  • Windows7
  • Windows8
  • Windows8.1
  • WindowsHomeServer
  • WindowsLiveWriter
  • WindowsPhone
  • WindowsServer
  • WinRT
  • WiX
  • WMI
  • WOPI
  • WPF
  • XAML
  • XBox360
  • XboxOne
  • zombie

Blog Archive

  • ▼  2013 (500)
    • ▼  December (12)
      • Free Export DataSet/DataTable/List<t> to Excel (wi...
      • wxHexEditor, your new large, 16EBs (exabytes) larg...
      • Think your passwords rock? Check out Telepathwords...
      • Rad Gate Post... Get your Red Gate Post here...
      • [Humor] A familiar looking Project Team?
      • Slicing .NET - NSlice, the Python like Slice for .Net
      • WiX'ing in VS 2013. WiX 3.8 adds VS 2013 support, ...
      • The TFS Upgrade Guide gets... well... upgraded. v3...
      • Windows 2012 Server Edition Comparison Matrix and ...
      • RegEx'ing - The RefCardz
      • 200 C# Video Tutorials? 200 VB? JavaScript? PHP? C...
      • What's the [table]diff? Diff'ing SQL Server tables...
    • ►  November (61)
    • ►  October (65)
    • ►  September (38)
    • ►  August (47)
    • ►  July (75)
    • ►  June (39)
    • ►  May (40)
    • ►  April (42)
    • ►  March (39)
    • ►  February (42)
Powered by Blogger.

About Me

Unknown
View my complete profile