Reputation: 407
I currently work on a .NET 4.7.1 application. Given is a for loop to compare 2 lists and to check if any Id has changed. If any Id in list 1 is different to any Id in list 2, I need to return null, otherwise the list 2.
I currently solved this issue with a simple for iteration. Nevertheless, I was wondering if I could solve this easier with a LINQ statement.
var list1 = new List<string>
{
"A",
"B",
"C"
};
var list2 = new List<string>
{
"A",
"C",
"B"
};
private List<string> Compare(){
if (list1 != null)
{
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] != list2[i])
{
return list2;
}
}
return null;
}
return list2;
}
Do you know how to solve this instead of a for loop, but with a LINQ statement?
Thanks!
Upvotes: 0
Views: 67
Reputation: 62472
You can use Zip
to group the items together to compare them, and then All
to make sure they're the same:
private List<string> Compare()
{
if (list1 == null) return list2;
if (list1.Count != list2.Count) return null;
bool allSame = list1.Zip(list2, (first, second) => (first, second))
.All(pair => pair.first == pair.second);
return allSame ? list2 : null;
}
NOTE: The Zip
function is used to place both items into a tuple (first, second).
You can also use SequenceEqual
private List<string> Compare()
{
if (list1 == null) return list2;
bool allSame = list1.SequenceEqual(list2);
return allSame ? list2 : null;
}
Upvotes: 3
Reputation: 9754
This is one linq alternative to the For loop
private List<string> Compare()
{
if (list1 == null) return list2;
if (list1.Where((x, i) => x != list2[i]).Any())
{
return list2;
}
return null;
}
Upvotes: 4