【问题标题】:LINQ select into arrayLINQ 选择到数组中
【发布时间】:2016-11-18 19:27:36
【问题描述】:

我正在尝试修改 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" }

感谢任何帮助。

【问题讨论】:

  • 所以你想要一个所有 PrimaryFields 的列表,以及所有不为空或 null 的 SecondaryFields?
  • 你的标题和你的问题都不清楚,我并没有真正看到代码块和输出之间的关系,但是你在寻找类似.SelectMany(p => new[] { p.PrimaryField, p.SecondaryField).Where(p => !string.IsNullOrWhitespace(p))的东西吗?
  • @CodeCaster 这就是我的想法。
  • 现在试试,感谢 CodeCaster
  • @CodeCaster 您的示例还将删除 null 或空的 PrimaryField 值,如果这是 OP 想要的,那很好。然而,这个问题只提到了 null 或空的 SecondaryFields。

标签: c# linq


【解决方案1】:

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

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();

你选择一个包含两个属性值的新数组,然后过滤掉你不想要的值,再把结果变成一个数组。

【讨论】:

    【解决方案2】:

    这应该很简单 - 获取两个字段,使用 Where 删除 null/empties 并转换为数组:

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

    现场示例:http://rextester.com/MHM61977

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      相关资源
      最近更新 更多