简体   繁体   中英

What is the best way to remove items from a IEnumerable<SelectListItem>?

I have an asp.net-mvc website and i am trying to use a dual listbox plugin

I have an array of

IEnumerable<SelectListItem> allItems:

and I have an array of Ints

IEnumerable<int> selectedIds;

that represents the Selected Value that someone filtered by. My goal is to see if given these two imputs, I can create two IEnumerable

 IEnumerable<SelectListItem> selectedItems;
 IEnumerable<SelectListItem> nonSelectedItems;

that I would use to populate the dual listbox plugin. I can get the selectedItems pretty easily but when i try to create the nonselected List i try to use Except() but it doesn't seem to be able to take the full list and "subtract" any item in the selected list.

Am I using the wrong method to do this filter?

You're looking for Where() :

allItems.Where(o => !selectedIds.Contains(int.Parse(o.Value)))

You can compute both sublists at once using ToLookup :

var lookup = allItems.ToLookup(o => selectedIds.Contains(int.Parse(o.Value)));
var selectedItems = lookup[true];

You can make these much faster by changing the IEnumerable<int> to a HashSet<int> so that Contains() becomes O(1). Just make sure not to covarinatly lose that .

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