Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 List<string> with a LIKE clause

Tags:

c#

list

linq

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.

like image 283
CatchingMonkey Avatar asked Sep 09 '13 13:09

CatchingMonkey


4 Answers

var results = files.Where(x => fileStub.Any(y => x.Contains(y))).ToList();
like image 72
MarcinJuraszek Avatar answered Oct 11 '22 12:10

MarcinJuraszek


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)));
like image 40
Raphaël Althaus Avatar answered Oct 11 '22 12:10

Raphaël Althaus


var result = files.Where(item => fileStub.Any(stub => item.Contains(stub))).ToList();
like image 28
metacircle Avatar answered Oct 11 '22 11:10

metacircle


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();
like image 1
Maarten Avatar answered Oct 11 '22 12:10

Maarten