0

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
George Silva
  • 3,454
  • 10
  • 39
  • 64
  • Why can't you just do: if (a[0] == a[1]) { ... }? – Eric J. Sep 16 '09 at 19:53
  • 1
    You just put 4 spaces in front of anything you want to show up formatted as code - the "101010" button will do this for you automagically. – James Kolpack Sep 16 '09 at 19:54
  • 1
    Exact duplicate: http://stackoverflow.com/questions/1301316/c-equivalent-of-python-slice-operation – Andrew Hare Sep 16 '09 at 19:54
  • You can use LINQ to accomplish this. It's been covered on SO before: http://stackoverflow.com/questions/1301316/c-equivalent-of-python-slice-operation As to your second question, you can mark parts of your post as code by either using the "Code Sample" button in the formatting bar (for code blocks) or by using backticks -- `` (for inline code). – Donut Sep 16 '09 at 19:56
  • @Eric J. because i need to do this with the elements of a variable sized list, in a automated manner. – George Silva Sep 16 '09 at 20:09
  • @George: For "inline" code, use backticks. For code blocks, use 4-space indents. Have edited your post - take a look at the edited version (i.e. hit edit to look at the markdown) to see what I've done. – Jon Skeet Sep 16 '09 at 21:37
  • Does this answer your question? [C# equivalent of rotating a list using python slice operation](https://stackoverflow.com/questions/1301316/c-sharp-equivalent-of-rotating-a-list-using-python-slice-operation) – Siyu Jul 09 '20 at 11:26

2 Answers2

4

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 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 Silva Sep 16 '09 at 21:40
  • @George: you can email me (skeet@pobox.com) 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 Sep 16 '09 at 22:10
  • @JonSkeet I realize this is pretty old, but what you describe above is almost exactly what I was trying to design when I came across this question. I looked at your latest version of MiscUtil... Range (which apparently dates from 2007) doesn't seem to be the same thing. Is this something you ever got around to, or have the newer versions of .NET/C#/LINQ provided this functionality in some other way? Thanks – brichins Mar 09 '12 at 22:26
  • @brichins: Nope, I didn't I'm afraid, and LINQ still doesn't. – Jon Skeet Mar 09 '12 at 22:33
0

I've been looking for something like Python-Slicing in C# with no luck. I finally wrote the following string extensions to mimic the python slicing:

static class StringExtensions
{
    public static string Slice(this string input, string option)
    {
        var opts = option.Trim().Split(':').Select(s => s.Length > 0 ? (int?)int.Parse(s) : null).ToArray();
        if (opts.Length == 1)
            return input[opts[0].Value].ToString();     // only one index
        if (opts.Length == 2)
            return Slice(input, opts[0], opts[1], 1);       // start and end
        if (opts.Length == 3)
            return Slice(input, opts[0], opts[1], opts[2]);     // start, end and step
        throw new NotImplementedException();
    }
    public static string Slice(this string input, int? start, int? end, int? step)
    {
        int len = input.Length;
        if (!step.HasValue)
            step = 1;
        if (!start.HasValue)
            start = (step.Value > 0) ? 0 : len-1;
        else if (start < 0)
            start += len;
        if (!end.HasValue)
            end = (step.Value > 0) ? len : -1;
        else if (end < 0)
            end += len;
        string s = "";
        if (step < 0)
            for (int i = start.Value; i > end.Value && i >= 0; i+=step.Value)
                s += input[i];
        else 
            for (int i = start.Value; i < end.Value && i < len; i+=step.Value)
                s += input[i];
        return s;
    }
}

Examples of how to use it:

"Hello".Slice("::-1");  // returns "olleH"
"Hello".Slice("2:-1");  // returns "ll"
thepirat000
  • 12,362
  • 4
  • 46
  • 72