LINQ: Checking if a string (variable) contains any of the list of properties
I need to check if my "constant" contains (string) of any items of my collection. My constant is here:
studentTest = "MathsTest"; // THis is a constant that doesn't change,
// it is set on frmL开发者_StackOverflow社区oad
Now my linq I require it to see if studentTest contains a string that is in my Tests (collection) with property of Name.
Now the studentTest is always "something" with the "Test" appended to the end i.e MathsTest, EnglishTest etc.
My Tests is a List of "Test", each test has a property called "Name" which has the name of the Test minus the word Test i.e. English , Maths etc and "NOT" EnglishTest, MathsTest.
So I need to check if my "constant" -- contains any text which is available in the property "Name" on each test.
I tried playing around here, but I am a little lost and this is the wrong direction.
if ( test.Tests.Any(x => x.Type.Contains(studentTest)) )
There are many ways to solve this; one approach is to remove the "Test" suffix from studentTest
and search for it:
string type = studentTest.substring(0, studentTest.Length - 4);
if (test.Tests.Select(t => t.Type).Contains(type)) { ... }
or, if you prefer to use Any()
:
if (test.Tests.Any(t => t.Type == type)) { ... }
Actually, the code you showed was almost correct, except that since it is the test name that is a substring of studentTest
, it should have been
if (test.Tests.Any(x => studentTest.Contains(x.Type))) { ... }
I would recommend using Substring()
, though, because the last approach would produce wrong results if one of the test types actually is "Test"
(very unlikely in your case, though)...
精彩评论