通过一个函数将列表中的每个元素传递,然后将其传递到另一个列表中。

huangapple go评论51阅读模式
英文:

Passing each element of a List through a function and then into another List

问题

我有一个TypeA的列表

List<A> ListA = new List<A> {
  new A("example1"), 
  new A("example2"), 
  new A("example3")
};

我需要将列表中的每个元素移动到一个TypeB的列表中,为此我需要将每个元素传递给一个名为convertAtoB(A a)的函数。如果A和B的列表是静态的,我可以像这样复制粘贴:

List<B> ListB = new List<B> {
  convertAtoB(ListA[0]),
  convertAtoB(ListA[1]),
  convertAtoB(ListA[2])
}

然而,这些列表的大小不是静态的。

我尝试使用Foreach

List<B> ListB = List<A>.Foreach(delegate(A a){
       return convertAtoB(a);
});

但是似乎Foreach不返回一个列表。

英文:

I have a List of TypeA

List&lt;A&gt; ListA = new List&lt;A&gt; {
  new A(&quot;example1&quot;), 
  new A(&quot;example2&quot;), 
  new A(&quot;example3&quot;)
};

And I have to move each element of the list to a List of TypeB to do this i need to put each element through a function convertAtoB(A a) so this would work if the List of A and B are static and I could just copy and paste like so

List&lt;B&gt; ListB = new List&lt;B&gt; {
  convertAtoB(ListA[0]),
  convertAtoB(ListA[1]),
  convertAtoB(ListA[2]),
}

However these Lists are not static in size.

I tried using Foreach

List&lt;B&gt; ListB = List&lt;A&gt;.Foreach(delegate(A a){
       return convertAtoB(a);
});

However it seems Foreach does not return a List.

答案1

得分: 3

LINQ有用于基本集合转换的工具。

使用 Select 进行映射操作,使用 ToList 将结果移动到新的集合中:

List<B> listB = listA.Select(convertAtoB).ToList();
英文:

LINQ has the tools for such basic collection transformations.

Use Select to perform a map, and the ToList to move results to a new collection:

List&lt;B&gt; listB = listA.Select(convertAtoB).ToList();

答案2

得分: 1

如果您想转换列表中的项目
>通过函数处理每个元素

您可以使用ConvertAll直接完成:

List<B> ListB = ListA.ConvertAll(convertAToB);
英文:

If you want to convert items of the list
>pass each element through a fuction

you can do it straitforward with a help of ConvertAll:

List&lt;B&gt; ListB = ListA.ConvertAll(convertAToB);

huangapple
  • 本文由 发表于 2023年5月14日 05:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定