How to compare the elements of each collection with each? A little explanation, I have a method that works with two objects, call it so objectname.method (objectname1) in the foreach loop, but it turns out that I take the same object, but there must be two different ones.

  • one
    Why don't you use the for loop? - sp7
  • and how do you want to compare them? One more or less than the other? Or are they equal? Sorting in the collection is needed? - Bulson
  • The question is not clear. Comparison means calling objectname.method (objectname1)? - Alexander Muksimov

2 answers 2

Keep in mind that if you use reference data types, the comparison compares the links, not the objects themselves. To compare objects, you need to write your comparator, which will compare them based on specific fields of the type.

For comparison, you can use the class Tuple<T> .

You can compare structures, they are compared by value, not by reference.

    Alas, I do not have telepathic abilities, but apparently you need something like this

      List<MyClass> lst = new List<MyClass>(); lst.Add(new MyClass(1)); lst.Add(new MyClass(2)); lst.Add(new MyClass(3)); lst.Add(new MyClass(4)); for (int i = 0; i < lst.Count; i++) { for (int j = i + 1; j < lst.Count; j++) { int compareResult = lst[i].method(lst[j]); } }