Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ดึงตัวอักษร 3 ตัวแรกจากทุกสตริงใน C#

นี่คือสตริงในลิสต์ของเรา:

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

เพื่อใช้ตัวอักษร 3 ตัวแรก ให้ใช้เมธอด Substring และใช้ภายใต้เมธอด Select ของ 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" };
        // ดึงตัวอักษร 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