English 中文(简体)
从清单上删除项目(净额2.0)
原标题:Remove items from list (.net 2.0)

我谨从符合某些条件的名单中删除项目。 我举了一个例子,说明我迄今所谈到的情况:

//remove 1´s and 3´s from list of ints

List<int> indexes = new List<int>();
List<int> ints = new List<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);

foreach (int i in ints)
{
    if(i == 1 || i == 3)
    indexes.Add(ints.IndexOf(i));
}

indexes.Reverse();

foreach (int index in indexes)
{
    ints.RemoveAt(index);
}

I am curious if the solution can be optimized? I cannot use System.Linq, I have only found the System.Data.Linq namespace as reference (Visual Studio 2005)

<>>>>>

I better had posted my real code. It is about deleting columns from a gridview

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

foreach (Type type in types)
{
     foreach (DataControlField c in entriesGrid.Columns)
     {
          string header = c.HeaderText;
          if (header == type.Name)
          {
              indexes.Add(entriesGrid.Columns.IndexOf(c));
          }
     }
}
最佳回答

为什么不使用<代码>List<T>Remove All(?

ints.RemoveAll(IsOneOrThree); // Remove all 1 s or 3 s

private static bool IsOneOrThree(int i)
{
    return i == 1 || i == 3;
}

如果它不这样简单(认为它实际上不是这样的话,你可以尝试):

for(int i= ints.Count - 1; i >= 0; i--)
{
    if(ints[i] == 1 || ints[i] == 3)
        ints.RemoveAt(i);
}

这节省了另一个名单和多个文件的费用。

问题回答

Try RemoveAll:

public bool MyPredicate(int i){
  return i == 3 || i == 5;
}

ints.RemoveAll(MyPredicate);

or if you have access to anonymous delegates:

ints.RemoveAll( (i) => i == 3 || i == 5 );

In addition, it is not usually a good idea to remove your question from SO, so that in the future people who might have the same question can read and learn from this.

下面可以找到驱逐所有人的更细微的例子(链接2.0):





相关问题
Autopaging or custom paging which is better in datagrid?

i used datagrid control in .net platform... but now i am in big confusion .. that is ..which is better to used custom or autopaging option.. gud explaination or example is needed.. i dont know ...

Gridview item preview using .net 2.0

I have a GridView control that for each item has a Hyperlinkfield with a URL to an aspx page. I want to (using AJAX libraries) to display the page preview in an inline window as the user hovers over ...

Rendering form to bitmap

I would like to render Form to bitmap... Is it possible in .net 2.0?

Transactions in .Net 2.0 application-- what to use?

I m working on a .Net 2.0 application and need to wrap some database transactions in my code. The backend is SQL Server 2008. I ve been away from .net for a few years, the last time I did any ...

Subsonic query: issue with the produced query

I m having a problem with subsonic query. The deal is, I have a view and I want to query it s data to produce something like the following SQL statement: select * from myView where (col1 like %a% ...

热门标签