简体   繁体   中英

make the remove from a list with condition in fastest way

Is there any alternative for deleting object from a list instead of what I have done with foreach;

I mean I don't think that the way I do is the best way and optimize way

like this:

var allobj= .. //this a list of all object
var myobj= .. //this a list of my selected object
foreach (var inu in myobj.ToArray())
{
    if (allobj.Where(p => p.UserName == inu.UserName).Count() != 0)
    {
        myobj.Remove(inu);
    }
}

Other answers have drawback, and that's "creating new collection excluding selected items" instead of removing items from actual collection.

This approach does not copy from main collection, it will remove items from list directly at optimum speed.

You will generate hashset from your selected items so that you can lookup strings in hashset at constant speed.

// generate hashset from selected items
var set = new HashSet<string>(myobj.Select(x => x.UserName));

// remove all items from list.
allobj.RemoveAll(x => set.Contains(x.UserName));

You cannot remove from the list you are iterating into.

Anyway you can construct a new list containing all the elements where username is not present in the global list:

var finalList = myobj.Where(obj => allobj.Any(o => o.UserName != 
obj.UserName)).ToList();

如果要从myobj中删除allobj存在UserName对象,则

var selected = myobj.Where(obj => allobj.Any(o => o.UserName == obj.UserName)).ToList();

If objects in those lists have the same reference, then to get all except selected items you can simply use:

var r = allItems.Except(selectedItems).ToList();

If they don't have the same reference, you can create the result this way:

var r = allItems.Where(x => !selectedItems.Any(y => y.UserName == x.UserName)).ToList();

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