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



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

第一个列表:

C:FolderFiles_01026666.pdf
C:FolderFiles_01027777.pdf
C:FolderFiles_01028888.pdf
C:FolderFiles_01029999.pdf

第二个列表:

01027777
01028888

列表结果应为:

C:FolderFiles_01027777.pdf
C:FolderFiles_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的比较。任何想法或任何你能给我指出的地方都将是一个很大的帮助。

我们可以将EndsWith()Path.GetFileNameWithoutExtension()一起使用,因为secondList中的字符串不是整个文件名。

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

尝试在线

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

似乎适用于字符串列表。在LINQ中使用Regex可能是个问题。例如,这在Linq2SQL中不起作用。

最新更新