ต่อไปนี้เป็นสตริงของเราในรายการ -
List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" }; หากต้องการใช้ตัวอักษร 3 ตัวแรก ให้ใช้วิธีสตริงย่อยและใช้ภายใต้วิธี 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" };
// 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