如何用LINQ使一些if(或表达式)更短
本文关键字:表达式 更短 if 何用 LINQ | 更新日期: 2023-09-27 18:17:44
我有一些像这样的c#行:
if (justification.Contains("CT_") ||
justification.Contains("CTPD_") ||
justification.Contains("PACS_") ||
justification.Contains("NMG_") ||
justification.Contains("TFS_ID") ||
justification.Contains("AX_") ||
justification.Contains("MR_") ||
justification.Contains("FALSE_POSITIVE") ||
justification.Contains("EXPLICIT_ARCH_TEAM_DESIGN_DECISON") ||
justification.Contains("EXPLICIT_ARCH_TEAM_DESIGN_DECISION"))
{
// justification is ok.
}else
{
reporter.Report(syntaxNode.GetLocation(), syntaxNode,
Resources.SpecifySuppressMessageJustificationTitle);
}
我的想法是把所有这些字符串到一个数组和在我的IF表达式我只是迭代我的数组(或枚举一个IEnumerable)。但是我该怎么做呢?
我从这里开始:
IEnumerable<string> someValues = new List<string>() { "CT_", "CTPD","PACS_", "NMG_", "AX_" };
if (justification == BUT HOW I HAVE TO RUN THROUGH MY someValuesand get the
stringValues?)
{
}
你可以这样做,如果你需要不区分大小写的包含检查,你可以通过使用justification.ToUpper()
获得大写,因为你已经有了大写的值列表
var someValues = new List<string>() { "CT_", "CTPD","PACS_", "NMG_", "AX_" };
if(someValues.Any(x=>justification.Contains(x))
{
// justification is ok.
}else
{
// not matching
}
var someValues = new[] { "CT_", "CTPD","PACS_", "NMG_", "AX_" };
if (someValues.Any(x => justification.Contains(x))
{
// justification is ok.
}
如果justification是IEnumerable(或List),您可以使用Intersect
Intercept生成一个集合,包含两个列表中都可以找到的项。
IEnumerable<string> someValues = new List<string>() { "CTPD","PACS_", "NMG_", "AX_"};
if (justification.Intersect(someValues).Any())
{
// Atleast one match was found.
}
如果对齐变量是字符串,可以使用Any()
if(someValues.Any(x => justification.Contains(x))
{
// A match was found.
}