Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq Contains without a variable name

I have this block of code which works

str1 = ["Element 1", "Element 2", "Element 3", "Element 4", "Element 5"];
var mystring = "Element 1";
bool found = str1.Contains(mystring);

I’d like to do this without having to use the variable str1 because I am working inside of a third-party tool for writing expressions that doesn’t allow creating variables and I need to hard code a list of elements. Note:mystring will be replaced by an input from the tool itself.

So something like this, but that actually works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["Element 1", "Element 2", "Element 3", "Element 4", "Element 5"].Contains(mystring);

Can this be done?

>Solution :

The most compact syntax to do that would be:

(new [] {"Element 1", "Element 2", "Element 3", "Element 4", "Element 5"}).Contains(mystring);

Whether your third-party tool would allow it is another question. Unfortunately there’s not yet a syntax in C# for collection "constants" like Python and other languages.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading