English 中文(简体)
我如何在C#中打下一个名单?
原标题:How do I truncate a list in C#?

我在下午知道,你可以做些什么,例如<条码>,[201:],但在C#中没有任何类似之处?

最佳回答
var itemsOneThroughTwenty = myList.Take(20);
var itemsFiveThroughTwenty = myList.Skip(5).Take(15);
问题回答

您可使用List<T>GetRange():

var subList = myList.GetRange(0, 20);

来自MSDN:

创建源代码中一系列内容的复印件。

<代码>公开 List<T> GetRange(int index, intgin)

如果你真的希望搁置名单,不提供副本,这可能有助于提高效率。 虽然金字节的例子提供了一份副本,但原始问题实际上是关于缩小名单范围的问题。

鉴于清单和编号;及

list.RemoveRange( 20, list.Count-20 );

这确实存在。 这仍然是O(n),因为必须删除对每个物体的提及,但应当比任何其他方法更快。

LINQ 快速......

    while (myList.Count>countIWant) 
       myList.RemoveAt(myList.Count-1);
    public static IEnumerable<TSource> MaxOf<TSource>(this IEnumerable<TSource> source, int maxItems)
    {
        var enumerator = source.GetEnumerator();            
        for (int count = 0; count <= maxItems && enumerator.MoveNext(); count++)
        {
            yield return enumerator.Current;
        }
    }

清单可使用<代码>RemoveRange关键词加以压缩。 该职能如下:

  void List<type>.RemoveRange(int index, int count);

This removes the elements from index until count. Using this for type int, to remove from 0 to the not required points:

法典:

int maxlimit = 100;
List<int> list_1 = new List<int>();
if (list_1.Count > maxLimit){
    list_1.RemoveRange(0, (list_1.Count - maxlimit));
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签