CompareWith

Compares two collections using the given comparison function, element by element.

Returns the first non-zero result from the comparison function.

WARNING

This function causes IEnumerable<T> evaluation.

Parameters

Returns

Func<T, T, int > comparer

IEnumerable<T> source1

IEnumerable<T> source2

int

Usage

The comparer function must receive an element of each collection and returns an integer value related to this comparison.

This function was inspired by compareWith function available at F# List module.

Comparing two different collections

//IEnumerable<int> source = { 1, 2, 4 }
//IEnumerable<int> source2 = { 1, 2, 3 }

int result = source.CompareWith(source2,
      (element1, element2) => element1 > element2 ? 1
                            : element1 < element2 ? -1
                            : 0 );

// result = 1

Comparing two different collections and getting the difference

//IEnumerable<int> source = { 1, 42, 3 }
//IEnumerable<int> source2 = { 1, 2, 3 }

int result = source.CompareWith(source2,
      (element1, element2) => element1 - element2);

// result = 42

It is important to notice that, the result is 42 because the first subtraction returns 0.

Last updated