简体   繁体   中英

Best way to emulate the functionality of Python's “in” keyword in C#?

Looked around but didn't see this asked. I'm essentially wondering what the 'best' (fastest, most readable, most idiomatic, etc) way of doing this would be.

The context is that I have a LINQ query to filter based on a list of possible enum values and want to keep it as un-nested as possible. In python, it'd be something like

def GetItems(status_types:list)
    return filter(lambda item: item.Status in status_types, ALL_ITEMS)

I think in C# I might have to do an

ALL_ITEMS
    .Where(i => Enum.GetValues(typeof(StatusEnum)
    .Intersect(status_types))
    .Contains(i.Status));

Is this reasonable? It seems a bit obtuse to me, though it might just be my own personal obtuseness coming into play.

edit I think I'm using Any() wrong here. Looking for the right linq thingo now, sorry. Changed to Contains, and added typeof(). That's what I get for just typing into the text box I guess.

I'm not sure why you are overcompicating things using Intersect , since you are only interested in findinf IF status_types contains i.Status , not in the set intersection of them.

Anyway, both these should do the job, even though the first form looks simpler ( I came up with the second since you mentioned the use of Any):

ALL_ITEMS
  .Where(i => status_types.Contains(i.Status));

or

ALL_ITEMS
  .Where(i => status_types.Any(x=>x==i.Status));
var itemsWithCorrectStatus = collection.Where(i=>status_types.Contains(i.Status));

This iterates over each item in collection, and checks whether i.Status is in status_types. If it is, include it. If not, exclude it.

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