Tuple<int, double>[] obs1;
Tuple<int, double>[] obs2;
我想做的是创建Tuple<int, double>[] obs3
包含在Tuple<int,double>
和int
中具有相同obs1
的{{1}}个,然后将相应的double设置为:
obs2
我尝试用这种方式找到相关的元组:
obs3[i].Item2 = obs1[i].Item2 + obs2[i].Item2
但是我不知道如何访问和使用var obs3 = from o in obs1 where obs2.Contains(o) select o;
,而只是获得Item2 double
的子集。
我一直对我的问题低估。我希望这是因为我没有尝试过第一次尝试解决方案。
答案 0 :(得分:9)
您可以在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();
答案 1 :(得分:0)
你可以使用下面的两个循环(不是基于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();
}