开发者

Separate groups of objects based on their properties

开发者 https://www.devze.com 2023-02-03 07:46 出处:网络
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:

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.


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.


I find this the easiest way to do it:

yourCollection.ToLookup(i => i.Person);
0

精彩评论

暂无评论...
验证码 换一张
取 消