Linq 将数组匹配到列表?
我有一个 List
和一个 FileInfo[]
。我需要知道 FileInfo[]
的全部内容是否都在 List
中。最 LINQy 且无错误的方法是什么?
我正在这样做,根据这里的响应,它返回 false,但是,我希望它返回 true:
// I want to know if all of these files are in the directory
List<string> allFilesWanted = new List<string>();
allFilesWanted.Add( "a1.txt" );
allFilesWanted.Add( "a2.txt" );
// Simulate a list of files obtained from the directory
FileInfo[] someFiles = new FileInfo[3];
someFiles[0] = new FileInfo("a1.txt");
someFiles[1] = new FileInfo( "a2.txt" );
someFiles[2] = new FileInfo( "notinlist.txt" );
// This returns "false" when I would expect it to return "true"
bool all = someFiles.All( fi => allFilesWanted.Contains<string>( fi.Name ) );
谢谢。
I have a List<string>
and a FileInfo[]
. I need to know if the entire contents of the FileInfo[]
are in the List<string>
. What is the most LINQy and error-free way to do that?
I was doing this, based on responses here, it returns false however, I expected it to return true:
// I want to know if all of these files are in the directory
List<string> allFilesWanted = new List<string>();
allFilesWanted.Add( "a1.txt" );
allFilesWanted.Add( "a2.txt" );
// Simulate a list of files obtained from the directory
FileInfo[] someFiles = new FileInfo[3];
someFiles[0] = new FileInfo("a1.txt");
someFiles[1] = new FileInfo( "a2.txt" );
someFiles[2] = new FileInfo( "notinlist.txt" );
// This returns "false" when I would expect it to return "true"
bool all = someFiles.All( fi => allFilesWanted.Contains<string>( fi.Name ) );
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您更新的问题:
您可能需要将
Name
替换为FullName
,具体取决于您的HashSet
包含的内容。还有区分大小写的问题。您可以在创建哈希集时提供自定义相等比较器以实现不区分大小写的比较(例如
StringComparer.InvariantCultureIgnoreCase
)。问题是您无法知道文件名是否区分大小写。这取决于所使用的文件系统。即使您知道它不区分大小写,用于不区分大小写比较的区域设置也可能会有所不同。或者仅使用 Linq:
Except
在内部使用 HashSet,所以这是 O(n)With your updated question:
You might need to replace
Name
withFullName
depending on what yourHashSet
contains.And there is the issue of case sensitivity. You can supply a custom equality comparer when creating the hashset to achieve a case insensitive comparison(such as
StringComparer.InvariantCultureIgnoreCase
). The problem is that you can't know if a filename is case sensitive or not. That depends on the used file system. And even if you know it's case insensitive the locale used for case insensitive compares can vary.Or just with Linq:
Except
uses a HashSet internally, so this is O(n)