Reputation: 772
I am trying to find the best way to compare values in 2 integer lists and return the list as soon as I find value in one list is bigger than the other
[1,2,3] and [1,2,4]
return second list [1,2] are equal but 4 in second list is greater than 3 in first list
[4,2,3] and [1,5,6]
return first list because the 4 in first list is greater than 1 in second list. No need to check other elements.
Now I can use a loop here but I am sure there is a better way using Linq.
Upvotes: 1
Views: 163
Reputation: 1
You can try this simple solution, I am considering that list can be null and of different length.
public static List<int> GetBiggerList(List<int> ls1, List<int> ls2)
{
if (ls1 == null)
return ls2;
if (ls2 == null)
return ls2;
int length = Math.Min(ls1.Count, ls2.Count);
for (int i = 0; i < length; i++)
{
if (ls1[i] > ls2[i])
return ls1;
if (ls2[i] > ls2[i])
return ls2;
}
if (ls1.Count > ls2.Count)
return ls1;
return ls2;
}
Upvotes: 1
Reputation: 39277
Assuming the two lists are the same length, you can find the first element that's not equal using LINQ:
var firstDifference = array1.Zip(array2, (a,b) => (a,b))
.SkipWhile(x => x.a == x.b).FirstOrDefault();
After that it's easy to handle the three cases: default
, a<b
, a>b
.
Edit: To handle these three cases you could do:
int firstDifference = array1.Zip(array2, (a,b) => (a,b))
.SkipWhile(x => x.a == x.b)
.Select(x => x.a.CompareTo(x.b)) // -1 or +1
.FirstOrDefault(); // 0 if no elements
This gives 0, -1 or +1 because default(int)
is 0
.
Upvotes: 2
Reputation:
Without Linq
static int[] Compare(int[] list1, int[] list2)
{
if ( list1 == null && list2 == null ) return null;
if ( list1 == null ) return list2;
if ( list2 == null ) return list1;
for ( int index = 0; index < list1.Length && index < list2.Length; index++ )
{
int compareValue = list1[index].CompareTo(list2[index]);
if (compareValue == 0) continue;
if (compareValue > 0) return list1;
return list2;
}
int compareLength = list1.Length.CompareTo(list2.Length);
if ( compareLength == 0 ) return null;
if ( compareLength > 0 ) return list1;
return list2;
}
Test
var list1 = new int[] { 1, 2, 3 };
var list2 = new int[] { 1, 2, 4 };
var list3 = new int[] { 4, 2, 3 };
var list4 = new int[] { 1, 5, 6 };
var list5 = new int[] { 1, 2 };
Action<int[]> print = list =>
{
Console.WriteLine(list == null ? "Same" : string.Join(",", list));
};
print(Compare(list1, list2));
print(Compare(list3, list4));
print(Compare(list1, list5));
print(Compare(list5, list1));
print(Compare(list1, list1));
print(Compare(null, list1));
print(Compare(list1, null));
print(Compare(new int[0], list1));
print(Compare(list1, new int[0]));
Output
1,2,4
4,2,3
1,2,3
1,2,3
Same
1,2,3
1,2,3
1,2,3
1,2,3
Upvotes: 0