代码之家  ›  专栏  ›  技术社区  ›  AndreyAkinshin

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

  •  3
  • AndreyAkinshin  · 技术社区  · 14 年前

    我有 List

    n=3 :

    [1, 2, 3, 4, 5] => [1, 2, 3]
    [1, 2] => [1, 2]
    

    最短的方法是什么?

    5 回复  |  直到 14 年前
        1
  •  13
  •   Daniel Earwicker    14 年前

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

    var list = new [] {1, 2, 3, 4, 5};
    
    var shortened = list.Take(3);
    

    请参见: http://msdn.microsoft.com/en-us/library/bb503062.aspx

    如果你有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;
        }
    }
    

    唯一的区别是它不是一个扩展方法:

    var shortened = SomeClass.Take(list, 3);
    
        2
  •  7
  •   Simon    14 年前

    如果没有LINQ,请尝试:

    public List<int> GetFirstNElements(List<int> list, int n)
    {
        n = Math.Min(n, list.Count);
        return list.GetRange(0, n);
    }
    

    否则使用Take。

        3
  •  6
  •   CaffGeek    14 年前

    你可以用Take

    myList.Take(3);
    
        4
  •  1
  •   David Basarab    14 年前

    你可以和林克一起

    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>();
    
        5
  •  1
  •   kemiller2002    14 年前
    var newList = List.Take(3);