gpt4 book ai didi

c# - LINQ 选择数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:59 24 4
gpt4 key购买 nike

我正在尝试修改 LINQ 查询以将某些属性选择到数组中,但我正在努力实现其中的一部分。

    toRun.AddRange(entity.Properties
.Select(property => property.PrimaryField)
.Select(field => new { field, entity = entity.EntityName, table = field.Table, key = entity.EntityIdField })

我需要进行此修改,以便如果名为 SecondaryField 的第二个属性不是 null 或空字符串,它将被添加到第一个 Select 语句的结果中。

例如,如果 entity.Properties 包含:

    Property { PrimaryField = "a", SecondaryField = "b" },
Property { PrimaryField = "c", SecondaryField = "" }

我希望第一个 Select 语句返回:

    { "a", "b", "c" }

感谢任何帮助。

最佳答案

这似乎重现了您想要的:您有一个具有两个属性的类:

public class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
}

你有一个收藏:

var foos = new List<Foo>
{
new Foo { Bar = "a", Baz = "b" },
new Foo { Bar = "c", Baz = "" },
};

并且从这个集合中,您想要选择所有具有非空值的属性到一个数组中。

您可以使用 SelectMany() 这样做:

var result = foos.SelectMany(f => new[] { f.Bar, f.Baz })
.Where(p => !string.IsNullOrWhiteSpace(p))
.ToArray();

您选择一个包含两个属性值的新数组,然后过滤掉您不想要的值,然后将结果重新转换为一个数组。

关于c# - LINQ 选择数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40675751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com