[英]How can I get one type of the child from a list by lambda?
Here is the code:这是代码:
private struct Child {
public string A;
public string B;
public boolean C;
}
List<Child> Test=new List<Child>();
Now I want to get all the string
A from the List<Child> Test
.现在我想从
List<Child> Test
中获取所有string
A 。
I have to do it like this yet:我必须这样做:
List<string>NewList=new List<string>();
foreach(Child C in Test)
{
NewList.Add(C.A);
}
It is so troublesome that I wanna whether there is a way faster, for example by using the lambda?太麻烦了,我想是否有更快的方法,例如使用 lambda?
Thank you.谢谢你。
var NewList = Test.Select(x => x.A).ToList();
but this is not faster, only a little less code.但这并不是更快,只是代码少了一点。
As mentioned in this Answer: https://stackoverflow.com/a/1178913/3121280如本答案所述: https://stackoverflow.com/a/1178913/3121280
you can do it like this:你可以这样做:
NewList = Test.Select(
x => x.A
).ToList();
Select
shown by others is what you need here, but it's worth mentioning SelectMany
for the moments where you need granchildren.其他人展示的
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)));
}
The snippet above outputs the following:上面的代码段输出以下内容:
C1_C1, C1_C2, C2_C1, C2_C2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.