LINQ How to combine the second element in a Tuple after a query, using where on the first element

 Tuple<int, double>[] obs1;
 Tuple<int, double>[] obs2;

I would like to create Tuple<int, double>[] obs3

which contains those Tuple<int,double>that have the same intin obs1and in obs2, and then set the corresponding double as:

obs3[i].Item2 =  obs1[i].Item2 + obs2[i].Item2

I tried to find the appropriate tuples this way:

var obs3 = from o in obs1 where obs2.Contains(o) select o;

But then I don’t know how to access and use Item2 double, instead I just get a subset obs1.

I continue to face my problems. I hope so because I have not tried to imagine the first attempt at a solution.

+4
source share
2 answers

You can join both arrays on Item1

var query = from t1 in obs1
            join t2 in obs2 on t1.Item1 equals t2.Item1
            select Tuple.Create(t1.Item1, t1.Item2 + t2.Item2);

Tuple<int, double>[] obs3 = query.ToArray();
+9
source

, , ( Linq)

    static void Main(string[] args)
    {
        Tuple<int, double>[] obs1 = new Tuple<int, double>[] { new Tuple<int, double>(1, 1.2), new Tuple<int, double>(2, 1.5), new Tuple<int, double>(3, 2.2) };
        Tuple<int, double>[] obs2 = new Tuple<int, double>[] { new Tuple<int, double>(1, 2.1), new Tuple<int, double>(2, 5.1), new Tuple<int, double>(4, 2.2) }; ;
        Tuple<int, double>[] obs3 = new Tuple<int, double>[obs1.Count()];

        for (int i = 0; i < obs1.Count(); i++)
        {
            for (int j = 0; j < obs2.Count(); j++)
            {
                if (obs1[i].Item1 == obs2[j].Item1)
                {
                    obs3[i] = new Tuple<int, double>(obs1[i].Item1, obs1[i].Item2 + obs2[j].Item2);
                    break;
                }
            }
        }

        foreach (var item in obs3)
        {
            Console.WriteLine(item?.Item1 + "\t" + item?.Item2);
        }
        Console.ReadKey();
    }
0

Source: https://habr.com/ru/post/1681347/


All Articles