英文:
How to verify the presence of a string in a constant list of strings
问题
以下是翻译好的代码部分:
// 第一个尝试
if (Destination.Name in new[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" })
// 经过一些搜索后的尝试
if (new[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }.Contains(Destination.Name))
在C#中,这是完成你所需任务的两种最简单的方式之一。
英文:
This should be easy, but I don't find the correct syntax: I would like to know if my name is present in a contant list of strings.
These are my attempts:
// first idea
if (Destination.Name in {"MA", "MB", "MC", "MD", "ME", "MF", "MG"})
// after some searching
if IndexOf(new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }, Destination.Name)
... but none of them seems to work.
What's the easiest way to get this done in C#?
Thanks in advance
答案1
得分: 4
如果我理解正确,您正在寻找Destination.Name
在"MA","MB","MC","MD","ME","MF","MG"
中的情况(即如果Destination.Name
是MA
或MB
等):
if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }.Contains(Destination.Name))
{
...
}
对于IndexOf
也是类似的,我们检查Destination.Name
在数组中的索引是否不为负数:
// 要么使用List,要么比较繁琐
// if (Array.IndexOf(new string[] {...}, Destination.Name)) {...}
if (new List<string> { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
.IndexOf(Destination.Name) >= 0)
{
...
}
最后,在一般情况下,您可以使用Linq查询数组。虽然这里有点过头了,但如果您有非平凡的条件,Lambda函数(这里是item => item == Destination.Name
)可能会非常灵活。
using System.Linq;
...
// 如果数组中有任何与Destination.Name相等的项
if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
.Any(item => item == Destination.Name))
{
...
}
英文:
If I understand you right, you are looking for Destination.Name
in "MA", "MB", "MC", "MD", "ME", "MF", "MG"
(i.e. if Destination.Name
is MA
or MB
etc.):
if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }.Contains(Destination.Name))
{
...
}
Same for IndexOf
: we check if Destination.Name
index within the array is not negative:
// Either use List, or ugly
// if (Array.IndexOf(new string[] {...}, Destination.Name)) {...}
if (new List<string> { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
.IndexOf(Destination.Name) >= 0)
{
...
}
Finally, in general case you can query array with a help of Linq.
It's an overshoot here, but if you have a non-trivial condition, lambda
function (here it is item => item == Destination.Name
) could be very flexible.
using System.Linq;
...
// If the array has any item which is equal to Destination.Name
if (new string[] { "MA", "MB", "MC", "MD", "ME", "MF", "MG" }
.Any(item => item == Destination.Name))
{
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论