代码如下:
private struct Child {
public string A;
public string B;
public boolean C;
}
List<Child> Test=new List<Child>();
现在我想从string
获得所有List<Child> Test
A。
我还必须这样做:
List<string>NewList=new List<string>();
foreach(Child C in Test)
{
NewList.Add(C.A);
}
这很麻烦,我想知道是否有更快的方法,例如使用lambda?
谢谢。
答案 0 :(得分:3)
var NewList = Test.Select(x => x.A).ToList();
但这并不快,只减少了一点代码。
答案 1 :(得分:1)
如本答案所述: https://stackoverflow.com/a/1178913/3121280
您可以这样做:
class Paddle(pygame.sprite.Sprite):
def __init__(self, x_pos, colors, SCREEN_HEIGHT):
self.colors = colors
...
self.image.fill(self.colors["WHITE"])
self.rect.y = SCREEN_HEIGHT/2
def paddle_hit(self):
...
self.image.fill(self.colors["RED"])
...
答案 2 :(得分:1)
Select
是您在这里需要的,但是值得一提的是SelectMany
。
private class Child
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
public static void Main()
{
var children = new List<Child>(){
new Child{
Name = "C1",
Children = new List<Child>{
new Child{ Name = "C1_C1"},
new Child{ Name = "C1_C2"}
}},
new Child{
Name = "C2",
Children = new List<Child>{
new Child{ Name = "C2_C1"},
new Child{ Name = "C2_C2"}
}}
};
var granchildren = children.SelectMany( c => c.Children);
Console.WriteLine(string.Join(", ", granchildren.Select(c => c.Name)));
}
上面的代码段输出以下内容:
C1_C1, C1_C2, C2_C1, C2_C2