查找变量名数组中是否不存在文件名
问题描述:
我有一个压缩文件列表,其中包含一个ZipArchive
和压缩的filename as a String
。我也有我需要检查我的列表的文件名的最终列表,如果文件不匹配我的文件名的最终列表,他们应该从我的压缩文件列表中转储。查找变量名数组中是否不存在文件名
我站在那可能不是最好的措辞,所以让我尝试解释我的代码/伪代码。
这里是我的清单:
List<ZipContents> importList = new List<ZipContents>();
它有两个参数:
-
ZipArchive
这就是所谓ZipFile
-
String
被称为FileName
filenames
是我试图检查我的ZipContents
列表的文件名的压轴列表。
这里是什么,我试图做的开始:
foreach (var import in importList)
{
var fn = import.FileName;
// do some kind of lookup to see if fn would be List<String> filenames
// If not in list dump from ZipContents
}
注释掉部分是什么我不确定这样做。有人能够帮助我走上正轨吗?谢谢!
编辑1
我知道我最初没有说,但我认为LINQ将采取更清洁的路线。我只是不积极如何。我假设使用.RemoveAll(..)
将是我想要去的方式?
答
你可以这样做:
if (!filenames.Contains(fn)) {
importList.Remove(import);
}
另外,我相信你可以使用LINQ简化这个逻辑逼到一条线。
编辑:
是的,你可以创建你想要的那些,像这样的一个新的列表:
var newImportList = importList.Where(il => filenames.Contains(il.FileName)).ToList();
答
您可以在一行中做到这一点。只需使用LINQ重新建立你的列表:
var filenames = new List<string> {"file1", "file2"};
var zipcontents = new List<ZipContents>
{
new ZipContents {FileName = "file1"},
new ZipContents {FileName = "file2"},
new ZipContents {FileName = "file3"}
};
zipcontents = zipcontents.Where(z => filenames.Contains(z.FileName)).ToList();
//zipcontents contains only files that were in 'filenames'
老实说,这是LINQ的:查询数据。
答
反向循环通过importList
,并在filenames
中找不到时删除项目。假设你没有太多项的表现应该是罚款:
for (int i = importList.Count - 1; i >= 0; i--)
{
if (!filenames.Contains(importList[i].FileName))
{
importList.RemoveAt(i);
}
}
使用foreach
,因为它修改集,就无法删除列表中的项目,但你可以在我的例子中,结构做。
这正是我要写的。如果这不是你的答案,我相信它会让你走上正轨。 – 2014-12-01 18:49:53
我喜欢你用'.Remove()'解决我的问题的方式,但是如果有很多内容,然后一个被删除并且顺序改变,这会在我的列表中导致问题吗? – scapegoat17 2014-12-01 19:01:45
如果您要从列表中删除项目,那么无论您做什么,它都会发生变化。使用.remove()应该保留顺序,但只是删除有问题的项目。但是,正如在另一个答案中指出的那样,这可能会通过修改您在foreach中迭代的列表而导致问题。我建议更好的方法是使用Linq,就像我编辑的代码一样。 – Redit0 2014-12-01 20:33:01