nbg15 nbg15 - 20 days ago 5
C# Question

How to make some if (or expressions) shorter with LINQ?

I have some c# lines like this:

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);
}


my idea was to put all these strings into an arra and at my IF Expression i just iterate my array (or enumerate an IEnumerable). But how can I Do this?

i started with this here:

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?)
{

}

Answer

you can do as below, if you need case insensitive contains check you can get upper case by using justification.ToUpper() since you already having value list in upper case

var someValues = new List<string>() { "CT_", "CTPD","PACS_", "NMG_", "AX_" };
if(someValues.Any(x=>justification.Contains(x))
{
   // justification is ok.
}else
{
   // not matching
}
Comments