LINQ:检查字符串(变量)是否包含任何属性列表
我需要检查我的“常量”是否包含(字符串)我的收藏中的任何项目。我的常量在这里:
studentTest = "MathsTest"; // THis is a constant that doesn't change,
// it is set on frmLoad
现在我的 linq 我需要它来查看 StudentTest 是否包含我的测试(集合)中具有 Name 属性的字符串。
现在,studentTest 始终是“某物”,末尾附加“测试”,即 MathsTest、EnglishTest 等。
我的测试是“测试”列表,每个测试都有一个名为“名称”的属性,其中包含测试的名称减去“测试”一词即英语、数学等,而不是“英语测试”、“数学测试”。
因此,我需要检查我的“常量”是否包含每次测试的属性“名称”中可用的任何文本。
我尝试在这里玩,但我有点迷失,这是错误的方向。
if ( test.Tests.Any(x => x.Type.Contains(studentTest)) )
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 frmLoad
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)) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法可以解决这个问题;一种方法是从
studentTest
中删除“Test”后缀并搜索它:或者,如果您更喜欢使用
Any()
:实际上,您显示的代码几乎是正确,只是因为测试名称是
studentTest
的子字符串,所以我应该建议使用
Substring()
,因为最后一种方法会如果其中一种测试类型实际上是“Test”,则会产生错误的结果(但在您的情况下不太可能)...There are many ways to solve this; one approach is to remove the "Test" suffix from
studentTest
and search for it:or, if you prefer to use
Any()
: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 beenI 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)...