1

I want to separate an array of my custom object into several arrays, based on the values of their two properties. The struct looks like this:

struct MyStruct {

    public string Person {
        get;
        set;
    }
    public string Command {
        get;
        set;
    }
}

Now, if I have an array with a few objects:

{Person1, cmd1}
{Person1, cmd3}
{Person2, cmd3}
{Person3, cmd2}
{Person2, cmd4}

I want to be able to place them into one array for each person, that lists all of the commands for that person:

{Person1: cmd1, cmd3}
{Person2: cmd3, cmd4}
{Person3: cmd2}

I hope I've made it clear with my descriptions. I would assume that there is an elegant way to do this with LINQ, but I have no idea where to start.

Bevin
  • 952
  • 6
  • 19
  • 35
  • Take a look at [this question](http://stackoverflow.com/questions/46130/how-do-i-group-in-memory-lists) - is that what you're looking for? – Aaron Jan 07 '11 at 23:54
  • Please don't create mutable structs. http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil – Ani Jan 08 '11 at 00:05
  • @ani only problem i see here is that the set-properties are public, but other than that the grouping wont change anything on the original structs !? – Pauli Østerø Jan 08 '11 at 00:15
  • @Pauli Østerø: No, they won't. I only brought this up in the interests of best practice. – Ani Jan 08 '11 at 00:16

2 Answers2

2
IEnumerable<MyStruct> sequence = ...

var query = sequence.GroupBy(s => s.Person)
                    .Select(g => new 
                                 { 
                                    Person = g.Key,
                                    Commands = g.Select(s => s.Command).ToArray() 
                                 })
                    .ToArray();

A similar query in query syntax:

var query = from s in sequence
            group s.Command by s.Person into g
            select new { Person = g.Key, Commands = g.ToArray() };

var queryArray = query.ToArray();

Do note that you asked for an array of arrays, but the result here is an array of an anonymous type, one of whose members is an array of strings.


On an another note, it's usually not recommended to create mutable structs.

Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307
0

I find this the easiest way to do it:

yourCollection.ToLookup(i => i.Person);
Jacob
  • 77,566
  • 24
  • 149
  • 228