.net - 将多个数组聚合为一个数组 (Linq)

标签 .net linq c#-3.0

我在将多个数组聚合成一个“大数组”时遇到了麻烦,我认为这在 Linq 中应该是可能的,但我无法理解它:(

考虑一些返回一些虚拟对象数组的方法

public class DummyObjectReceiver 
{
  public DummyObject[] GetDummyObjects  { -snip- }
}

现在我在某个地方有这个:

public class Temp
{
  public List<DummyObjectReceiver> { get; set; }

  public DummyObject[] GetAllDummyObjects ()
  {
    //here's where I'm struggling (in linq) - no problem doing it using foreach'es... ;)
  }
}

希望我想要实现的目标有点清楚 (作为额外的,我想通过 DummyObject 具有的 int 值对该数组进行排序... - 但 orderby 应该没有问题,...我希望;)

最佳答案

您使用SelectMany方法将返回对象的数组列表展平为一个数组。

public class DummyObject {
    public string Name;
    public int Value;
}

public class DummyObjectReceiver  {

    public DummyObject[] GetDummyObjects()  {
        return new DummyObject[] {
            new DummyObject() { Name = "a", Value = 1 },
            new DummyObject() { Name = "b", Value = 2 }
        };
    }

}

public class Temp {

    public List<DummyObjectReceiver> Receivers { get; set; }

    public DummyObject[] GetAllDummyObjects() {
        return Receivers.SelectMany(r => r.GetDummyObjects()).OrderBy(d => d.Value).ToArray();
    }

}

示例:

Temp temp = new Temp();
temp.Receivers = new List<DummyObjectReceiver>();
temp.Receivers.Add(new DummyObjectReceiver());
temp.Receivers.Add(new DummyObjectReceiver());
temp.Receivers.Add(new DummyObjectReceiver());

DummyObject[] result = temp.GetAllDummyObjects();

关于.net - 将多个数组聚合为一个数组 (Linq),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/781116/

相关文章:

c# - .NET:静态方法的推断泛型类型

c# - RESTful 网络服务

迁移到 .Net4 后出现 C# 错误 "Is not supported by the language"

c# - 错误 : "The specified LINQ expression contains references to queries that are associated with different contexts"

c# - 为什么这个Linq表达式比另一个表达式慢很多?

c# - 试图理解约束点——我走在正确的轨道上吗?

c# - 以编程方式更改 Windows 10 锁屏背景(在桌面上)

c# - 如何在 WPF 中自动检测 Flowdirection RightToLeft 或 LeftToRight

c# - 如何在 C# 4 中对 T 执行动态 where lambda?

c# - string.Replace 不适用于报价