Reputation:
I have two lists-
List<String> List1;
List<File> List2;
The contents are as follows-
List1 List2
----- -----
String ID FileName LastWrite
tttaaaajk34j34 1 aaa 01-02-2019
oooccc 2 bbb 14-09-2018
ddd 3 ccc 23-06-2019
ttt 4 ddd 15-10-2016
aaa2832kajj 5 eee 20-08-2012
I want to compare List1 with List2 and remove items from List2 that are found in the List1.
Result-
List2
----
ID FileName
2 bbb
4 ddd
5 eee
My Code-
List1.Where(f => !List1.Any(str => str.FileName.Contains(List2)))
The Problem-
This doesn't work. It throws below exception as List2 is a List, unlike List1 which is List.
'String does not contain a definition for filename and no extension method filename accepting a first argument of type string..
Upvotes: 0
Views: 1904
Reputation: 26315
You could just filter out the files using LINQ:
List1.Where(f => !List2.Any(str => str.Contains(f.FileName)))
Explanation:
Enumerable.Where()
to first filter out the files from List1
, you want to keep.String.Contains()
to check if Enumerable.Any()
of the files from List2
have substring filenames FileName
from List1
. In this case we make sure to use !
operator in the predicate to ensure we don't keep files that have been found in List2
. UPDATE
As per updated requirements in the question just switch around List1
and List2
. Your new query should be:
List2.Where(f => !List1.Any(str => str.Contains(f.FileName)))
Upvotes: 6