2011-01-07 115 views
1

我想基於它們的兩個屬性的值將我的自定義對象的數組分成幾個數組。該結構是這樣的:基於屬性的單獨對象組

struct MyStruct { 

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

現在,如果我有幾個對象的數組:

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

我希望能夠把它們放在一個陣列的每個人,列出所有對於那個人的命令:

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

我希望我已經說清楚了。我會認爲有一個優雅的方式來與LINQ做到這一點,但我不知道從哪裏開始。

+0

看看[這個問題](http://stackoverflow.com/questions/46130/how-do-i-group-in -memory-lists) - 你在找什麼? – Aaron 2011-01-07 23:54:41

回答

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

在查詢語法類似的查詢:

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

請注意,你問一個數組的數組,但這裏的結果是一個匿名類型的數組,一個其成員是字符串數組。


另一方面,通常是not recommended to create mutable structs

0

我這才發覺這樣做最簡單的方法:

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