Compare two generic Lists
Hi ,how I can compare two 开发者_高级运维Lists, the first type ICollections <T>
the other List<T>
see if they contain the same records
using Linq
Assuming ICollection<T> x
and List<T> y
...
If order of the records matters:
return x.SequenceEqual(y);
If order doesn't matter, I think your best option is to skip LINQ and use a HashSet<T>
:
return new HashSet<T>(x).SetEquals(y);
Here is a sample code depending on whether sequence is important or not :
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));
}
As suggested by other colleagues also consider using HashSet<T>
. Just take into account that HashSet
is available only starting from .NET Framework 3.5.
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");
}
use this type of concept....
OR
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");
}
try this one also.....
ICollection<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6 };
List<int> list2 = new List<int>() { 6, 7, 8, 9 };
bool contains = list1.Any(e => list2.Any(d => d.Equals(e)));
精彩评论