English 中文(简体)
如何从收集中删除x项?
原标题:How to remove x items from collection using LINQ?
  • 时间:2011-11-21 13:33:57
  •  标签:
  • c#

是否有办法将除第一类以外的所有物品从任何种类的收集中去除(Control)。 仅使用LINQ的项目、清单......?

最佳回答

How about something using reflection?

static void RemoveButFirst(object o){

    Type t = o.GetType();

    System.Reflection.MethodInfo rm = t.GetMethod("RemoveAt",
                                                 new Type[]{typeof(int)});
    System.Reflection.PropertyInfo count = t.GetProperty("Count");

    for (int n = (int)(count.GetValue(o,null)) ; n>1; n--)
        rm.Invoke(o, new object[]{n-1});

}   

这将在您的收集暴露了<条码>英寸的财产和<条码>RemoveAt(int)方法,我认为这些收集方法应当采用。

更简明的版本,使用dynamic

public static void RemoveBut(dynamic col, int k){
    for (int n = col.Count; n>k; n--)
        col.RemoveAt(n-1);
}
问题回答

准则编号为查询(无副作用)而不是添加或删除项目。

你们可以做的是,撰写一个涉及收集工作的第一点内容的问询:

var result = source.Take(1);

请注意,LINQ不从事各类收集工作;需要一个LINQ提供商来进行LINQ的工作。 例如,source 必须实施IEvidable<T> 采用

如何(在林克):

var result = list.Where(l => l != list.First());

But this would be better:

var result = list.Take(1);
        List<string> collection = new List<string>();
        collection.RemoveAll(p => p.StartsWith("something"));
listXpto.Where(x=>true /* here goes your query */)
    .Select(x=>{listXpto.Remove(x); return null})

但我不知道这一点的真正效用。

认为移走的方法是国际男女同性恋者,而不是一般的教义。





相关问题
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. ...

热门标签