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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With