[英]How to packing the results of List.ForEach() to a new list?
I'm learning C#. 我正在学习C#。
I have two lists of same type. 我有两个相同类型的列表。
struct Foo
{
string fKey;
Bar bVal;
}
List<Foo> f1; List<Foo> f2;
Now f1 and f2 contains same number of elements, with each fKey in f1 present in f2 also, but in a different position. 现在f1和f2包含相同数量的元素,f1中的每个fKey也存在于f2中,但位置不同。
What I want to do is to join these two lists on the fKey, do some operation on the Bar values (some kind of merging), and store the results to a new List. 我想要做的是在fKey上加入这两个列表,对Bar值进行一些操作(某种合并),然后将结果存储到新的List中。
Foo Merge(Foo f1, Foo f2)
{
// Merge
return new Foo(f1);
}
For this I have reached until here. 为此,我到达了这里。
f1.Join(f2, oldFoo => oldFoo.fKey, newFoo => newFoo.fKey, (oldFoo, newFoo) => new { myOldFoo = oldFoo, myNewFoo = newFoo } // Join on the fKey attribute
).ToList(). // Dump the results to a list
ForEach(aPair => Merge(aPair.myNewFoo, aPair.myOldFoo));
In the imperative programming, I would push the return value of Merge() to a new List. 在命令式编程中,我会将Merge()的返回值推到新的List中。 How I can do that in this consruct?
在这个构想中我该怎么做?
Perform your Merge
operation within a Select
projection, then use ToList
to materialize the results into a list. 在“
Select
投影中执行“ Merge
操作,然后使用“ ToList
将结果具体化为列表。
var l = f1.Join(f2, oldFoo => oldFoo.fKey, newFoo => newFoo.fKey,
(oldFoo, newFoo) => new { myOldFoo = oldFoo, myNewFoo = newFoo })
.Select(aPair => Merge(aPair.myNewFoo, aPair.myOldFoo))
.ToList();
Edit : I assume you could combine the Merge
into the Join
for conciseness: 编辑 :为简单起见,我假设您可以将
Merge
到Join
中:
var l = f1.Join(f2, oldFoo => oldFoo.fKey, newFoo => newFoo.fKey,
(oldFoo, newFoo) => Merge(newFoo, oldFoo))
.ToList();
这正是ConvertAll()
函数的作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.