简体   繁体   English

在C#中模拟Python的“ in”关键字功能的最佳方法?

[英]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. 上下文是我有一个LINQ查询要根据可能的枚举值列表进行过滤,并希望使其尽可能不嵌套。 In python, it'd be something like 在python中,它将类似于

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 我认为在C#中,我可能必须做一个

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. 编辑我认为我在这里使用Any()错误。 Looking for the right linq thingo now, sorry. 很抱歉,现在寻找正确的linq somethingo。 Changed to Contains, and added typeof(). 更改为包含,并添加了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. 我不确定您为什么要使用Intersect来过度梳理事物,因为您只对findinf感兴趣,如果status_types包含i.Status而不是它们的集合相交。

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): 无论如何,尽管第一种形式看起来更简单(尽管您提到了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. 这将遍历集合中的每个项目,并检查i.Status是否在status_types中。 If it is, include it. 如果是这样,请将其包括在内。 If not, exclude it. 如果不是,将其排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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