11

I'm having trouble aggregating multiple arrays into one "big array", I think this should be possible in Linq but I can't get my head around it :(

consider some method which returns an array of some dummyObjects

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

now somewhere I have this:

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... ;)
  }
}

hope it's somewhat clear what I'm trying to achieve (as extra I want to order this array by an int value the DummyObject has... - but the orderby should be no problem,... I hope ;)

2
  • 2
    I think I just answered this very question: stackoverflow.com/questions/780867 Commented Apr 23, 2009 at 10:23
  • Yes, it's the same principle, but this one has the added twist of having a list of objects with a method that returns the arrays. Commented Apr 23, 2009 at 11:18

1 Answer 1

16

You use the SelectMany method to flatten the list of array returning objects into an array.

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

}

Example:

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();
Sign up to request clarification or add additional context in comments.

2 Comments

+1. I missed the "multiple" aspect in my now deleted answer.
exactly what I was looking for :) extra thanks for including orderby! (still can only +1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.