V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
vtoexsir
V2EX  ›  C#

c#里是否有类似 Python 中 list 的切片操作

  •  
  •   vtoexsir · 2020-02-25 16:55:55 +08:00 · 10417 次点击
    这是一个创建于 1494 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如 python 中,list1 = ['abc', 'blas', 'dsl'],
    要将每个元素的第一个字符变成大写 list2 = ['Abc', 'Blas', 'Dsl'],
    只需要如下操作即可:
    list2 = [x[0].upper() + x[1:] for x in list1]

    请问 c#里是否也有类似简洁明了的语法来实现?多谢!

    6 条回复    2020-07-27 08:21:10 +08:00
    hahastudio
        1
    hahastudio  
       2020-02-25 17:09:17 +08:00   ❤️ 1
    如果你在用 C# 8.0,那么有 x[1..^0]
    不然的话,基本就是 Skip().Take() 了
    xupefei
        2
    xupefei  
       2020-02-25 17:13:55 +08:00   ❤️ 1
    > var list = new []{"aaa","bbb","ccc"};
    > var list2 = list.Select(t=>Char.ToUpper(t[0])+t[1..]);

    Aaa
    Bbb
    Ccc
    xupefei
        3
    xupefei  
       2020-02-25 17:17:06 +08:00   ❤️ 1
    @xupefei 或者用很像 py 的语法:
    var list3 = from t in list select Char.ToUpper(t[0])+t[1..];
    forgottencoast
        4
    forgottencoast  
       2020-02-26 10:04:55 +08:00   ❤️ 1
    C# 8.0 才能用类似 Python 的切片的写法。
    低版本只能用字符串的 Substring 方法来代替了。
    类似:
    from t in list select Char.ToUpper(s[0]) + t.Substring(1);

    其实这些自己写一个帮助方法也不费事,并不需要特别简明的语法。
    charlie21
        5
    charlie21  
       2020-04-11 22:06:45 +08:00
    ```
    using System.Linq;
    static void Test()
    {
    string[] arr = { "abc", "blas", "dsl" };
    arr = arr.Select(i => Char.ToUpper(i[0]) + i[1..]).ToArray();
    Array.ForEach(arr, Console.WriteLine);
    }

    ```
    output:
    Abc
    Blas
    Dsl
    mingl0280
        6
    mingl0280  
       2020-07-27 08:21:10 +08:00
    @xupefei 正解,linq 就行了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2897 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:58 · PVG 21:58 · LAX 06:58 · JFK 09:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.