在 C# 中获取每个字符串的前三个字母

csharpprogrammingserver side programming更新于 2025/5/22 4:22:17

以下是列表 − 中的字符串

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

要使用前 3 个字母,请使用 substring 方法并在 Linq Select 方法下使用它。

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" };
      // 从每个字符串中获取前 3 个字母
      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

相关文章