[英]Shorthand way of adding strings from class into List<string>?
I have the following C# code: 我有以下C#代码:
List<string> names = new List<string>();
if (myObject.myClass != null)
{
foreach (var foo in myObject.myClass.subClass)
{
names.Add(foo.Name);
}
}
Is there a shorter way of writing this without the need to iterate through each instance of subClass
to add myObject.myClass.subClass.Name
into the names
List<string>
object? 是否有更短的编写方式,而无需遍历每个
subClass
实例以将myObject.myClass.subClass.Name
添加到names
List<string>
对象中?
Also baring in mind myObject.myClass
can be null. 同时考虑到
myObject.myClass
也可以为null。
It sounds like you could use: 听起来你可以使用:
List<string> names = myObject.myClass == null
? new List<string>()
: myObject.myClass.subclass.Select(x => x.Name).ToList();
Note that this expression: myObject.myClass.subclass
suggests you're violating the Law of Demeter fairly nastily - and I hope the naming doesn't actually reflect reality though... if you could provide a more indicative set of expressions, that would help a lot. 请注意,这个表达式:
myObject.myClass.subclass
表明你违反了得墨忒耳法 - 我希望命名实际上并不能反映现实......如果你能提供更具指示性的表达式,那就是帮了很多忙。
You can use the AddRange
method to add all elements of an IEnumerable
to a list: 您可以使用
AddRange
方法将IEnumerable
所有元素添加到列表中:
if (myObject.myClass != null) {
names.AddRange(myObject.myClass.subClass.Select(c => c.Name));
}
您可以在List上使用AddRange方法。
您可以使用LINQ来构建列表,但请注意,它仍然是枚举以构建列表:
var names = myObject.myClass.subClass.Select(x => x.Name).ToList();
It's not clear what is a collection and what is not. 目前尚不清楚什么是集合,什么不是。 So i assume that
myObject.myClass
is already a collection( IEnumerable<myClass>
) and can be null and myClass.subClass
is an IEnumerable<subClass>
and you want all of their names. 所以我假设
myObject.myClass
已经是一个集合( IEnumerable<myClass>
),并且可以为null, myClass.subClass
是一个IEnumerable<subClass>
,你想要他们所有的名字。
var classNames = from c in myObject.myClass
where c != null
from subC in c.subClass
where subC != null
select subC.Name;
List<String> names = classNames.ToList();
This is a LINQ query, it's the equivalent of Enumerable.SelectMany
in method syntax. 这是一个LINQ查询,它等同于方法语法中的
Enumerable.SelectMany
。
Note that you need to add using System.Linq
. 请注意,您需要
using System.Linq
添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.