gpt4 book ai didi

c# - 从 IEnumerable 中进行选择时避免重复自己

转载 作者:太空宇宙 更新时间:2023-11-03 20:00:26 27 4
gpt4 key购买 nike

我有一个 IEumerable<XElement>称为 foo .

我有这个代码

foo.Select(x => new
{
bars = x.Descendants(namespace + "bar") != null
? x.Descendants(namespace + "bar").Select(z => z.Value).ToArray()
: new string[0]
})
.ToArray();

我怎样才能把这个写得更整洁一点?我真的不想重复这部分

x.Descendants(namespace + "bar")

最佳答案

使用额外的Select:

foo.Select(x => x.Descendants(namespace + "bar"))
.Select(x => new
{
bars = x != null ? x.Select(z => z.Value).ToArray() : new string[0]
})
.ToArray();

或者:

foo.Select(x =>
{
var elements = x.Descendants(namespace + "bar");
return new
{
bars = elements != null ? elements.Select(z => z.Value).ToArray() : new string[0]
}
})
.ToArray();

顺便说一句,我不认为 Descendants 会返回 null。您可能应该检查是否有任何元素使用 Any 方法。

 bars = x.Any() ? x.Select(z => z.Value).ToArray() : new string[0]

关于c# - 从 IEnumerable 中进行选择时避免重复自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29103066/

27 4 0