开发者

Remove an object from a collection

I want to remove an objec开发者_开发百科t from a collection if the object does'nt satisfies some condition

      foreach (var data in infData)
          {
            if(data.Id==0)
             {
               //Remove this object from the collection
             }
          }

How to do this.

EDIT: This is the complete code

foreach (var data in infData)
        {
            //Validate Offence Code
            IQueryable<Ref_OffenceCode> allRows = dbContext.Ref_OffenceCode;
            if (allRows.Where(p => p.Code == data.offenceCode && p.StartDate<=data.offenceDate ).Count() == 0)
            {
                invalidCount += 1;
            }

            //Validate Location Code
            //IQueryable<Ref_OffenceCode> allRows = dbContext.Ref_OffenceCode;
            if (invalidCount != 0)
            {
                infData.Remove(data);
            }
        }


Instead of removing the object from the collection you could create a new filtered collection:

var filteredList = infData.Where(x => x.Id != 0);

and leave the GC take care of the old collection when it falls out of scope. Also you mentioned ArrayList in your post. Unless you are using .NET 1.1 or older there's absolutely no reason to use ArrayList. A generic collection would be more appropriate.


for List do this:

infData = infData.RemoveAll(p => p.Id == 0)

and in General you can do this (for enumerable):

enumerable = enumerable.Except(enumerable.Where(p => p.Id == 0));


Don't use foreach if you want to remove an item from a collection (since you are modifying the collection while iterating over it).

You can use an index based approach, but recall that the collection size will change. If you only need to remove one item, you can do this:

for (int i = 0; i < infData.Count; i++)
{
  if(infData[i].Id==0)
  {
    infData.RemoveAt(i);
    break;
  }
}

As @Stefano comments, you can iterate backwards and then you don't need to break (and can remove multiple items):

for (int i = infData.Count - 1; i >= 0 ; i--)
{
  if(infData[i].Id==0)
  {
    infData.RemoveAt(i);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜