嗨,我如何比较两个列表,第一个类型是ICollections <T>,另一个是List<T>,看看它们是否使用Linq包含相同的记录。
发布于 2011-06-24 03:17:09
假设ICollection<T> x和List<T> y..。
如果记录的顺序重要:
return x.SequenceEqual(y);如果订单不重要,我认为您最好的选择是跳过LINQ并使用HashSet<T>
return new HashSet<T>(x).SetEquals(y);发布于 2011-06-24 04:37:46
下面是一个示例代码,取决于序列是否重要:
ICollection<int> collection1 = new List<int> { 5, 1, 6, 7, 3 };
List<int> collection2 = new List<int> { 1, 5, 6, 7, 3 };
bool considerSequence = true; // sequence is important
bool areEquael;
if (considerSequence)
{
areEquael = collection1.SequenceEqual(collection2);
}
else
{
areEquael = collection1.OrderBy(val => val).SequenceEqual(
collection2.OrderBy(val => val));
}正如其他同事所建议的,也考虑使用HashSet<T>。只需考虑HashSet只能从.NET Framework3.5开始即可使用。
发布于 2011-06-24 03:16:12
List<Guid> lst = new List<Guid>();
List<Guid> lst1 = new List<Guid>();
bool result = false;
if (lst.Count == lst1.Count)
{
for (int i = 0; i < lst.Count; i++)
{
if (!lst[i].Equals(lst1[i]))
{
result = false;
break;
}
}
}
else
{
result = false;
}
if (result)
{
Response.Write("List are same");
}
else
{
Response.Write("List are not same");
}使用这种概念..。
或
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(51);
lst.Add(65);
lst.Add(786);
lst.Add(456);
List<int> lst1 = new List<int>();
lst1.Add(786);
lst1.Add(1);
lst1.Add(456);
lst1.Add(65);
lst1.Add(51);
bool result = false;
if (lst.Count == lst1.Count)
{
result = lst.Union(lst1).Count() == lst.Count;
}
if (result)
{
Response.Write("list are same");
}
else
{
Response.Write("list are not same");
}也试试这个..。
https://stackoverflow.com/questions/6462870
复制相似问题