C# 从C上的列表中获取前几个元素#

C# 从C上的列表中获取前几个元素#,c#,list,C#,List,我有一个包含n项的列表。我希望将我的列表转换为新列表,其中不超过n个项目 n=3示例: [1, 2, 3, 4, 5] => [1, 2, 3] [1, 2] => [1, 2] 最短的方法是什么?如果您有C#3,请使用Take扩展方法: var list = new [] {1, 2, 3, 4, 5}; var shortened = list.Take(3); var shortened = SomeClass.Take(list, 3); 见: 如果你有C#2,你可以

我有一个包含n项的
列表
。我希望将我的列表转换为新列表,其中不超过n个项目

n=3
示例:

[1, 2, 3, 4, 5] => [1, 2, 3]
[1, 2] => [1, 2]
最短的方法是什么?

如果您有C#3,请使用
Take
扩展方法:

var list = new [] {1, 2, 3, 4, 5};

var shortened = list.Take(3);
var shortened = SomeClass.Take(list, 3);
见:

如果你有C#2,你可以写出等价的:

static IEnumerable<T> Take<T>(IEnumerable<T> source, int limit)
{
    foreach (T item in source)
    {
        if (limit-- <= 0)
            yield break;

        yield return item;
    }
}
你可以用Take

myList.Take(3);
你可以和林克在一起

List<int> myList = new List<int>();

myList.Add(1);
myList.Add(2);
myList.Add(3);
myList.Add(4);
myList.Add(5);
myList.Add(6);

List<int> subList = myList.Take<int>(3).ToList<int>();
List myList=new List();
添加(1);
添加(2);
添加(3);
添加(4);
添加(5);
添加(6);
List subList=myList.Take(3.ToList();

如果您没有LINQ,请尝试:

public List<int> GetFirstNElements(List<int> list, int n)
{
    n = Math.Min(n, list.Count);
    return list.GetRange(0, n);
}
public List getfirstnements(List List,int n)
{
n=Math.Min(n,list.Count);
返回列表。GetRange(0,n);
}

否则使用Take。

不需要进行长度检查。在我看来,可以推断出许多泛型。这可以简化为myList.Take(3).ToList(),根据@Dave的注释。
var newList = List.Take(3);