tags:

views:

111

answers:

2

Sorry for such a basic question regarding lists, but do we have this feature in C#?

e.g. imagine this Python List:

a = ['a','b,'c']
print a[0:1]

>>>>['a','b']

Is there something like this in C#? I currently have the necessity to test some object properties in pairs. edit: pairs are always of two :P

Imagine a larger (python) list:

a = ['a','a','b','c','d','d']

I need to test for example if a[0] = a[1], and if a[1] = a[2] etc.

How this can be done in C#?

Oh, and a last question: what is the tag (here) i can use to mark some parts of my post as code?

+2  A: 

See here: c# slicing like python method

ennuikiller
+3  A: 

You can use LINQ to create a lazily-evaluated copy of a segment of a list. What you can't do without extra code (as far as I'm aware) is take a "view" on an arbitrary IList<T>. There's no particular reason why this shouldn't be feasible, however. You'd probably want it to be a fixed size (i.e. prohibit changes via Add/Remove) and you could also make it optionally read-only - basically you'd just proxy various calls on to the original list.

Sounds like it might be quite useful, and pretty easy to code... let me know if you'd like me to do this.

Out of interest, does a Python slice genuinely represent a view, or does it take a copy? If you change the contents of the original list later, does that change the contents of the slice? If you really want a copy, the the LINQ solutions using Skip/Take/ToList are absolutely fine. I do like the idea of a cheap view onto a collection though...

Jon Skeet
Python, as far as i am concerned Python only reads the list. It will only copy the list if you explicitely asks it to.In the example given print a[0:1] will print only the elements in that range. If you ask print a it will print the original elements in the list, a b and c.I would like to contribute to that Jon. How can we can in touch (in a more effective manner?)THanks for the interest!
George
@George: you can email me ([email protected]) but to be honest I don't think it should take long to write a simple implementation. I'll probably put it in MiscUtil (http://pobox.com/~skeet/csharp/miscutil) unless I can think of anywhere better. Will try to find some time over the weekend...
Jon Skeet