简体   繁体   中英

Compare 2 List<string> with a LIKE clause

I have 2 lists, one a list of file names, the second a list of file name stubs, i would like to select everything from the first list where the file name is like the file name stub.

List<string> files = new List<string>() {"a.txt", "b.txt", "c.txt"};
List<string> fileStub = new List<string>() {"a", "b", "c"};

The query would return all records from the first list.

Thanks in advance.

var results = files.Where(x => fileStub.Any(y => x.Contains(y))).ToList();

if the order is important (of course, with this sample, the size of the two lists is important, if you don't want IndexOutOfRange exceptions)

var res = files.Where((file, index) => file.Contains(fileStub[index]));

if you don't mind order (than list sizes are not important)

var res = files.Where(file => fileStub.Any(fs => file.Contains(fs)));
var result = files.Where(item => fileStub.Any(stub => item.Contains(stub))).ToList();

Use the Any and Contains methods.

List<string> files = new List<string>() {"a.txt", "b.txt", "c.txt"};
List<string> fileStub = new List<string>() {"a", "c"};
var result = files.Where(x => fileStub.Any(y => x.Contains(y))).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM