How to remove elements from an array

前端 未结 5 1156
闹比i
闹比i 2021-01-15 08:22

Hi I\'m working on some legacy code that goes something along the lines of

for(int i = results.Count-1; i >= 0; i--)
{
  if(someCondition)
  {
     result         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 09:09

    May I suggest a somewhat more functional alternative to your current code:

    Instead of modifying the existing array one item at a time, you could derive a new one from it and then replace the whole array as an "atomic" operation once you're done:

    The easy way (no LINQ, but very similar):

    Predicate filter = delegate(T item) { return !someCondition; };
    
    results = Array.FindAll(results, filter);
    // with LINQ, you'd have written: results = results.Where(filter);
    

    where T is the type of the items in your results array.


    A somewhat more explicit alternative:

    var newResults = new List();
    foreach (T item in results)
    {
        if (!someCondition)
        {
            newResults.Add(item);
        }
    }
    results = newResults.ToArray();
    

提交回复
热议问题