LINQ:检查字符串(变量)是否包含任何属性列表

发布于 2024-11-03 08:18:18 字数 587 浏览 0 评论 0原文

我需要检查我的“常量”是否包含(字符串)我的收藏中的任何项目。我的常量在这里:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万水千山粽是情ミ 2024-11-10 08:18:19

有很多方法可以解决这个问题;一种方法是从 studentTest 中删除“Test”后缀并搜索它:

string type = studentTest.substring(0, studentTest.Length - 4);
if (test.Tests.Select(t => t.Type).Contains(type)) { ... }

或者,如果您更喜欢使用 Any()

if (test.Tests.Any(t => t.Type == type)) { ... }

实际上,您显示的代码几乎是正确,只是因为测试名称是 studentTest 的子字符串,所以

if (test.Tests.Any(x => studentTest.Contains(x.Type))) { ... }

我应该建议使用 Substring(),因为最后一种方法会如果其中一种测试类型实际上是“Test”,则会产生错误的结果(但在您的情况下不太可能)...

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)...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文