简体   繁体   English

如何检查列表中是否已存在文件?

[英]How can i check if a files already exist in the List?

This is the code: 这是代码:

for (int i = 0; i < files.Count; i++)
{
    if (pdf1.Lightnings.Count == 0)
    {
        pdf1.Lightnings.Add(files[i]);
    }
    if (files[i] != pdf1.Lightnings[i])
    {
        pdf1.Lightnings.Add(files[i]);
    }
}

Both files and Lightnings are List<string> 文件和闪电都是List<string>

For example in files I have 33 indexes (files names) and I want to add them to the Lightnings List. 例如,在文件中,我有33个索引(文件名),我想将它们添加到“闪电列表”中。 But I want to check that if the file name from the List of files already exist in Lightnings so don't add it again. 但是我想检查一下Lightnings中是否已存在文件列表中的文件名,所以不要再次添加它。

The way it is now I'm getting error since when the variable i=1 so the line: 现在的方式是我得到错误,因为当变量i = 1时,该行:

if (files[i] != pdf1.Lightnings[i])

Throws an error since in Lightnings i have only one index [0] and in i=1 already 引发错误,因为在闪电中我只有一个索引[0]并且在i = 1中已经

You can use the .Contains method: 您可以使用.Contains方法:

if (!pdf1.Lightnings.Contains(files[i]))
    pdf1.Lightnings.Add(files[i]);

This will check that files[i] does not already exist in the collection before adding. 在添加之前,这将检查files[i]在集合中尚不存在。

You could try using distinct property and foreach loop: 您可以尝试使用与众不同的属性和foreach循环:

var count = 0;
foreach(var file in files.Distinct())
{

    if (pdf1.Lightnings.Count == 0)
    {
        pdf1.Lightnings.Add(file);
    }
    if (files[i] != pdf1.Lightnings[count])
    {
        pdf1.Lightnings.Add(file);
    }
    count++;
}
pdf1.Lightnings.AddRange(files.Distinct());

要么

pdf1.Lightnings = pdf1.Lightnings.Union(files));

This can be done pretty easily using LINQ, it will also reduce the amount of code you need to write eg 使用LINQ可以很容易地做到这一点,它还会减少您需要编写的代码量,例如

var itemsToAdd = files.Where(x => !pdf.Lightnings.Contains(x));
pdf.Lightnings.AddRange(itemsToAdd);

Even one line if you still found it readable 即使您仍然觉得可读,也只有一行

pdf.Lightnings.AddRange(files.Where(x => !pdf.Lightings.Contains(x)));

As an alternative to the answers already given, if you want a unique list of items, you could use HashSets instead. 作为已经给出的答案的替代方法,如果您想要一个唯一的项目列表,则可以改用HashSets Of course, whether the HashSet is better than a List depends on your usage, but it guarantees unique values. 当然,HashSet是否比List更好取决于您的用法,但它可以保证唯一的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM