3

So I just started in C# coming from a Matlab/Python background. What I do miss the most are advanced indexing queries like:

a = [1 2 3 4;5 6 7 8];
b = a[2,2:4]; // Gives: b = [6 7 8];

In C# (and most other programming languages) I have several possibilities to achieve that:

  • by using loops. Higher-dimensional arrays will yield lots of (similar) code
  • using LINQ: a big library, and the syntax still seems cumbersome and slow to me.
  • Extending the Array like here on dotnetperls.com, but this won't work with the bracket operator, but gets closer to the idea
  • Writing my own class, however I won't be able to inherit from System.Array

So to me it looks like it should be "doable" to implement a calls like this to arrays:

b = a["1,1:3"]; // compare to example above, just 0-based indexing here

So what I want to do is

  1. overload the Array class / Inherit a class from Array class (so it remains generic)
  2. add custom bracket indexing with string parsing

Without writing too much code. Am I missing something?

Please note: this is rather an exercise for me than an actual task. So I know I could use Python and compile the code. I am just wondering if it is possible at all and if so, which way is the best to do it.

Community
  • 1
  • 1
AnatraIlDuck
  • 283
  • 2
  • 8
  • [Or you could use Python while taking advantage of the .Net framework](http://ironpython.net/) – Nasreddine May 19 '16 at 20:48
  • Well you cannot inherit from Array or add an _indexer_ as an extension method to array. But you can inherit from List and add an indexer as you want to. Or write a wrapper around array which will delegate all functionality to the underlying array + add your indexer. – Evk May 19 '16 at 20:55
  • Probably better not to use strings, and use something like `b = a [1,slice(1,3)]`, or with extension methods, `b = a[1, (1).to(3)]` – Eric May 19 '16 at 22:29
  • @Evk: thanks, List are nice suggestions, however I'd have to put work in to make them multidimensional. The wrapper seems like a good solution, but still results in quite some overhead of what I actually want to achieve... – AnatraIlDuck May 20 '16 at 11:43
  • @Eric I agree, parsing a string gives extra work. I could consider writing a function for that, but again: this blows up the syntax/queries in a multidimensional array quite fast. Will consider it though – AnatraIlDuck May 20 '16 at 11:44
  • What do you mean by "blows up"? One problem is that you're basically forced to discard type safety and declare `this[params object[] objs]`, unless you want a bazillion different overloads – Eric May 20 '16 at 15:41
  • By "blowing up" I mean it adds more and more characters and makes code less compact... – AnatraIlDuck May 23 '16 at 11:54

0 Answers0