LINQ 查询查找列表中包含第二个列表中的子字符串元素的项目

发布于 2025-01-14 20:52:30 字数 902 浏览 1 评论 0原文

我试图列出第一个列表中的所有元素,其中包含等于第二个列表中所有元素的子字符串

第一个列表:

C:\Folder\Files_01026666.pdf
C:\Folder\Files_01027777.pdf
C:\Folder\Files_01028888.pdf
C:\Folder\Files_01029999.pdf

第二个列表:

01027777
01028888

列表结果应该be:

C:\Folder\Files_01027777.pdf
C:\Folder\Files_01028888.pdf

我得到的更接近的是 .Intersect() 但两个字符串元素应该相等

List<string> resultList = firstList.Select(i => i.ToString()).Intersect(secondList).ToList();

List<string> resultList = firstList.Where(x => x.Contains(secondList.Select(i=>i).ToString()));

List<string> resultList = firstList.Where(x => x == secondList.Select(i=>i).ToString());

我知道我可以用另一种方式做到这一点,但我想用 LINQ 来做到这一点。 我查看了其他查询,但我可以找到与 Linq 的密切比较。任何想法或任何你可以指出我的地方都会有很大的帮助。

I am trying to list all elements from the first list where it contains a substring equal to all elements from the second list

First list:

C:\Folder\Files_01026666.pdf
C:\Folder\Files_01027777.pdf
C:\Folder\Files_01028888.pdf
C:\Folder\Files_01029999.pdf

Second list:

01027777
01028888

List result should be:

C:\Folder\Files_01027777.pdf
C:\Folder\Files_01028888.pdf

the closer that I got was with .Intersect() but both string-element should be equals

List<string> resultList = firstList.Select(i => i.ToString()).Intersect(secondList).ToList();

List<string> resultList = firstList.Where(x => x.Contains(secondList.Select(i=>i).ToString()));

List<string> resultList = firstList.Where(x => x == secondList.Select(i=>i).ToString());

I know I can do this another way but I'd like to do it with LINQ.
I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

‖放下 2025-01-21 20:52:30

我们可以使用 EndsWith( )Path.GetFileNameWithoutExtension(),因为第二个列表中的字符串不是完整的文件名。

var result = firstList
    .Where(path => secondList.Any(fileName => Path.GetFileNameWithoutExtension(path).EndsWith(fileName)));

在线尝试

We can use EndsWith() with Path.GetFileNameWithoutExtension(), as strings in the secondList are not entire file names.

var result = firstList
    .Where(path => secondList.Any(fileName => Path.GetFileNameWithoutExtension(path).EndsWith(fileName)));

Try Online

栀子花开つ 2025-01-21 20:52:30
var q = list1.Where(t=>Regex.IsMatch(t,String.Join("|",list2.ToArray()))));

似乎适用于字符串列表。在 LINQ 中使用正则表达式可能会出现问题。例如,这在 Linq2SQL 中不起作用。

var q = list1.Where(t=>Regex.IsMatch(t,String.Join("|",list2.ToArray()))));

Seems to work for lists of strings. Using Regex can be problem in LINQ. This won't work in Linq2SQL for example.

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