獲取 C# 中每個字串中的前三個字母


以下是我們的字串列表 -

List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };

若要使用前 3 個字母,請使用 substring 方法,並將其用於 Linq 選擇方法。

IEnumerable<string> res = list.AsQueryable() .Cast<string>() .Select(str => str.Substring(0, 3));

示例

 演示

using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
      // getting first 3 letters from every string
      IEnumerable<string> res = list.AsQueryable() .Cast<string>() .Select(str =>       str.Substring(0,3));
      foreach (string str in res) {
         Console.WriteLine(str);
      }
   }
}

輸出

key
mou
joy
mon

更新於: 2020-6-23

2K+ 次瀏覽

開啟你的 職業

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.