簡體   English   中英

從fileinfo列表中刪除重復項

[英]Removing duplicates from fileinfo list

我正在從fileinfo列表中填充一個組合框-但是當我在索引的開頭添加-請選擇-時,它會給我重復項:

string[] filters = new[] { "*.html", "*.htm" };
string[] gettemplates = filters.SelectMany(f => Directory.GetFiles(emailTemplatesFolder, f)).ToArray();

List<System.IO.FileInfo> templates = new List<System.IO.FileInfo>();
FileInfo fi = new FileInfo("---Please Select---");
templates.Insert(0, fi);

foreach (string file in gettemplates)
{                        
   System.IO.FileInfo t = new System.IO.FileInfo(file);
   templates.Add(t);
}

BindingSource bs = new BindingSource();
bs.DataSource = templates;

comboEmailTemplates.DisplayMember = "Name";
comboEmailTemplates.ValueMember = "Filepath";
comboEmailTemplates.DataSource = bs;

試過

 List System.IO.FileInfo unique = templates.Distinct().ToList();

並綁定到新來源,但仍然帶來重復項。

我究竟做錯了什么?

謝謝

使用Distinct它將使用所討論類型的默認比較器。 在您的情況下,它是FileInfo ,不會覆蓋Object的默認值。 因此,比較僅供參考。 由於列表中的每個項目都是不同的實例(使用new關鍵字),因此它們是不同的。

快速解決方案-將字符串作為不同的集合:

filters.SelectMany(f => Directory.GetFiles(emailTemplatesFolder, f)).Distinct().ToArray();

總之,我會重構一下:

var templates = new List<FileInfo>();
templates.Insert(0, new FileInfo("---Please Select---"););

templates.AddRange(filters.SelectMany(f => Directory.GetFiles(emailTemplatesFolder, f))
                          .Distinct()
                          .Select(f => new FileInfo(f)));
BindingSource bs = new BindingSource();
bs.DataSource = templates;

問題在於列表中的所有元素都是不同的對象,並且Distinct()LINQ方法將在引用時對其進行比較。 解決方案是實現IEqualityComparer並使用Distinct()方法的重寫。 例如,如果您想按名稱進行比較。

public class FileNameComparer : IEqualityComparer<FileInfo>
{
   public bool Equals(FileInfo x, FileInfo y)
   {
      if (x == y)
      {
         return true;
      }

      if (x == null || y == null)
      {
         return false;
      }

      return string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase);
   }

   public int GetHashCode (FileInfo obj)
   {
      return obj.Name.GetHashCode ();
   }
}

然后像這樣使用它

List System.IO.FileInfo unique = templates.Distinct(new FileNameComparer()).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM