C# 程序从列表中获取前三个元素
csharpprogrammingserver side programming更新于 2025/9/16 17:50:00
使用 Take() 方法在 C# 中获取第一个元素的单独数量。
首先,设置一个列表并添加元素 −
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
myList.Add("Five");
myList.Add("Six");
现在,使用 Take() 方法从列表中获取元素。添加所需元素的数量作为参数 −
myList.Take(3)
以下是代码 −
示例
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
myList.Add("Five");
myList.Add("Six");
// 前三个元素
var res = myList.Take(3);
// 显示前三个元素
foreach (string str in res) {
Console.WriteLine(str);
}
}
}
输出
One Two Three

