M
M
Mister_krid2022-04-09 12:16:20
C++ / C#
Mister_krid, 2022-04-09 12:16:20

How does sequence difference work in Linq?

The method calculates the difference of two arrays. I don't understand how Except() works because it should remove duplicate elements if they are in two arrays (lists). But if I give it
{5, 5, 5} - { } it returns one five, but it should three because there is nothing in the second array and it should not delete anything. Explain, please.

public int[] ArrayDiff(int[] a, int[] b)
        {
            
            var result = a.Except(b);

            int[] outArray = new int[result.Count()];

           var i = 0;
            foreach (int res in result)
            {               
                outArray[i] = res;
                i++;
            }
            return outArray;
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2022-04-09
@Mister_krid

I did not go into the description of the function, but the example shows that it works exactly as you have:

double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };

IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);

foreach (double number in onlyInFirstSet)
    Console.WriteLine(number);

/*
 This code produces the following output:

 2
 2.1
 2.3
 2.4
 2.5
*/

Those. duplicate values ​​are "merged".
Apparently you did not understand its final purpose.

O
oleg_ods, 2022-04-10
@oleg_ods

Methods Except, Union, Substruct are designed to work with Sets.
A set, by definition, is a collection of unique(!) values.
That is, when calling the Except method, LINQ first converts the array {5, 5, 5} into a set (removes all duplicate elements => {5}, and then subtracts from it into a second array, which also first converts to a set (empty). Accordingly, after subtraction, the result remains {5}.
If you need to end up with {5, 5, 5} , then you need to use the option proposed above. If you need to do this often, then it makes sense to write your own extension for LINQ.

M
Mister_krid, 2022-04-12
@Mister_krid

if it’s not difficult, explain the difference between select and where, I realized that where returns only values ​​that satisfy the condition, and select returns ALL values, but sorting the ones we need first. And the moment that I didn’t understand, select returns bool, but it still use to get int, string, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question