简体   繁体   中英

.Net Framework 4.5.1 RemoveAt

I have migrated my MVC application from linq-to-Sql to EF 6.1.1, and from .Net Framework 4.0 to 4.5.1. I used the following to remove items from list:

 List<int> idsToKeep = new List<int>();
   for (int i = 0; i < visit.Client.Count; i++)
                {
                Client om = visit.Client[i];
                if (om.ClientId == 0)
                    continue;
                bool itemExists = false;
                foreach (int id in idsToKeep)
                    if (om.ClientId == id)
                        itemExists = true;
                if (!itemExists)
                    {
                    visit.Client.RemoveAt(i);
                    i--;
                    }
                }
                   return errors;
            }

Initially I got this error:

cannot apply indexing with to an expression of type system.collections.generic.iCollection

in this line:

  Client om = visit.Client[i];

Changed it to:

  Client om = visit.Client.ElementAt(i);

I am not sure this is correct, however did not get any error; the problem is I can not resolve RemoveAt in this line:

  visit.Client.RemoveAt(i);  

Would appreciate your suggestions

It seems visit.Client is an ICollection<T> and there is no RemoveAt method on ICollection<T> .You can try using ToList method to turn it into a List, or you can use linq to exclude items you want:

visit.Client = visit.Client.Where(x => x.ClientId == 0 ||
                                       idsToKeep.Contains(x.ClientId)).ToList();

Try this, the trick is you have to remove from bottom up...

        var visit = new Visit();
        List<int> idsToKeep = new List<int>();
        visit.Client.Reverse();
        foreach(var thing in visit.Client){
            Client om = thing;
            if (om.ClientId == 0)continue;
            bool itemExists = false;
            foreach (int id in idsToKeep)
                if (om.ClientId == id)
                    itemExists = true;
            if (!itemExists)
            {
                visit.Client.Remove(thing);
            }
        }
        return errors;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM