如何比较两个HashSet?

时间:2013-01-16 07:05:25

标签: c#

private void button1_Click(object sender, EventArgs e)
{
   string[] array1 = { "C:/folder/a.txt", "C:/folder/b.txt", "C:/folder/c.txt", "C:/folder/d.txt" };

   string[] array2 = { "D:/a.txt", "D:/b.txt", "D:/c.txt", "D:/d.txt" };

   var hash1 = new HashSet<string>(array1);

   var hash2 = new HashSet<string>(array2);

}

我想比较hash1hash2。如果a.txt上存在hash2文件,请从C:/folder/a.txt移除hash1。我们可以在没有迭代值的情况下这样做吗?

1 个答案:

答案 0 :(得分:0)

如果我没错,那应该是这样的:

var result = array1.Where(a1 =>  //take only those items from array1, which
              !array2.Any(     //have no such item in array2 
                a2 => a2.Contains(  //that contains
                   a1.Substring(a1.LastIndexOf("/"))))); //a similar filename

var hash1 = new HashSet<string>(result);
var hash2 = new HashSet<string>(array2);

也就是说,创建具有必要值的HashSet就足够了。所以所有的计算都是通过数组完成的。