110,546
社区成员
发帖
与我相关
我的任务
分享
public class MyComparer : IEqualityComparer<List<string>>
{
public bool Equals(List<string> x, List<string> y)
{
if (x.Count != y.Count) return false;
for (int i = 0, c = x.Count; i < c; i++)
{
if (!x[i].Equals(y[i]))
{
return false;
}
}
return true;
}
public int GetHashCode(List<string> obj)
{
if (Object.ReferenceEquals(obj, null)) return 0;
int code = 0;
foreach (string item in obj)
{
code ^= item.GetHashCode();
}
return code;
}
}
class Program
{
static void Main(string[] args)
{
List<List<string>> list1 = new List<List<string>>() {
new List<string>(){ "3", "1", "3" },
new List<string>(){ "1", "2" },
new List<string>(){ "0", "1", "2","4" }
};
List<List<string>> list2 = new List<List<string>>() {
new List<string>(){ "0", "1", "2","4" },
new List<string>(){ "0", "1", "3" },
new List<string>(){ "2", "1" }
};
List<List<string>> result = Enumerable.Intersect(list1, list2, new MyComparer()).ToList();
foreach (List<string> item in result)
{
Console.WriteLine("item:");
foreach (string sub in item)
{
Console.WriteLine(sub);
}
}
Console.Read();
}
}
//取交集
ArrayList al=new ArrayList();
ArrayList al1=new ArrayList();
ArrayList al2=new ArrayList();
int i;
for(i=0;i <10;i++)
{
al.Add(i);
}
for(i=5;i <20;i++)
{
al1.Add(i);
}
for(i=0;i <al.Count;i++)
{
if(al1.Contains(al[i]))
{
al2.Add(al[i]);
}
}
}
class myeqc : IEqualityComparer<List<string>> //自定义相等比较器
{
public bool Equals(List<string> list1, List<string> list2)
{
int i = 0; //看看两个集合有多少个元素相同
foreach (string s in list1)
{
foreach (string s2 in list2)
{
if (s == s2)
i++;
}
}
Console.WriteLine("正在比较:[{0}] 和 [{1}]", string.Join(",", list1.ToArray()), string.Join(",", list2.ToArray()));
Console.WriteLine("结果:{0}, 共{1}个元素,其中{2}个相同", i == list1.Count && i == list2.Count, Math.Max(list1.Count, list2.Count), i);
Console.WriteLine();
if (i == list1.Count && i == list2.Count)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(List<string> DF)
{
int hash = 0;
Console.WriteLine("正在获取[{0}]的哈希值,返回{1}", string.Join(", ",DF.ToArray()), hash);
return hash;
}
}