Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ选择进入阵列_C#_Linq - Fatal编程技术网

C# LINQ选择进入阵列

C# LINQ选择进入阵列,c#,linq,C#,Linq,我试图修改LINQ查询,以将一些属性选择到数组中,但我很难实现其中的一部分 toRun.AddRange(entity.Properties .Select(property => property.PrimaryField) .Select(field => new { field, entity = entity.EntityName, table = field.Table, key = entity.EntityIdField })

我试图修改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" }

感谢您的帮助。

这应该很简单-获取这两个字段,使用
Where
删除空/空字段,然后转到数组:

 var result = entity.Properties.SelectMany(p =>new[]{ p.PrimaryField,p.SecondaryField})
            .Where(x => !String.IsNullOrEmpty(x))
            .ToArray();

实例:

这应该非常简单-获取两个字段,使用
Where
删除空值/空值并转到数组:

 var result = entity.Properties.SelectMany(p =>new[]{ p.PrimaryField,p.SecondaryField})
            .Where(x => !String.IsNullOrEmpty(x))
            .ToArray();

实例:

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

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 = "" },
};

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

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

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(p=>new[]{p.PrimaryField,p.SecondaryField)。其中(p=>!string.IsNullOrWhitespace(p))
?@CodeCaster我就是这么想的。现在就试试吧,谢谢CodeCaster@CodeCaster您的示例还将删除null或空的PrimaryField值,如果OP希望这样,也可以。但是,问题只提到了null或空的SecondaryFields。因此,您需要一个包含所有PrimaryFields和所有SecondaryF的列表不是空或空的ield?你的标题和问题都不清楚,我也看不出代码块和输出之间的关系,但是你是在寻找类似
.SelectMany(p=>new[]{p.PrimaryField,p.SecondaryField)。Where(p=>!string.IsNullOrWhitespace(p))
?@CodeCaster我就是这么想的。现在就试试吧,谢谢CodeCaster@CodeCaster您的示例还将删除null或空的PrimaryField值,如果OP希望这样做,也可以。但是,问题只提到了null或空的SecondaryField。