简体   繁体   中英

How to filter out 2 ids in c#?

I have below code which is filtering out menu id value 8

oListVM = oListVM.Where(x => x.MenuID != 8).ToList();  //filter out menu id 8

But I wanted to filter out menu id 8 and 13 so I decided to write the code like this. Is this the right way to filter out both 8 and 13 menu id? I recently started working with c# and .net.

oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13

You could also do

oListVM = oListVM
    .Where(x => x.MenuID != 8)
    .Where(x => x.MenuID != 13)
    .ToList();  //filter out menu id 8 and 13

Link is evaluated when it is "accessed" - by .ToList() you access and persist the whole iteration at once. It makes no difference for the Linq-Statement if you cram all conditions into one Where conditional or if you chain them.

If you decide to also block 14, 18, 22 you could also use another linq to check if any is (not) in a list of things:

var doNotShow = new [] {8, 13, 14, 18, 22};
oListVM = oListVM
    .Where(x => ! doNotShow.Any(d => x == d))
    .ToList();

You are right

oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13

is a valid way to do. In additional, say you have more than 2 ids, just use Array or List :

int[] filterArray = new int[6] {1,5,6,8,13,14};
oListVM = oListVM.Where(x => !filterArray.Contains(x)).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