我有一个List<double>
和一个List<List<double>>
。举个例子,比如:
List<double> Label = new List<double>{ 1, 0, 1 };
和
List<List<double>> Matrix = new List<List<double>>
{
new List<double>{1.2, 1.5, 1.8},
new List<double>{1.5, 1.8, 1.2},
new List<double>{1.8, 1.2, 1.5}
};
我想合并这些列表,我想要的输出是这样的:
1 1.2 1.5 1.8
0 1.5 1.8 1.2
1 1.8 1.2 1.5
另外:两个列表中的数据量总是相同的。
您可以尝试一个简单的for
循环:
for (int r = 0; r < Matrix.Count; ++r) // for each row r in Matrix
Matrix[r].Insert(0, Label[r]); // we insert Label[r] item at 0th position
虽然我同意OP在问这个问题之前至少应该发布他/她的尝试,但我还是忍不住自己尝试了一下。这是我使用 Linq 的尝试:
List<double> Label = new List<double> { 1, 0, 1 };
List<List<double>> Matrix = new List<List<double>>
{
new List<double>{1.2, 1.5, 1.8},
new List<double>{1.5, 1.8, 1.2},
new List<double>{1.8, 1.2, 1.5}
};
var result = Label.Zip(Matrix, (l, m) => m.Prepend(l));
result
具有IEnumerable<IEnumerable<double>>
的类型。这个答案使用Zip()
来组合两个列表,方法是将第一个列表(double
(中的元素预置到第二个列表(List<double>
你去吧
@for(int i=0; i<Matrix.Count();i++) {
var val = Label.get(i); //get the corresponding value
Matrix[i].Insert(0,val); //insert val to beginning of this list entry
}