【问题标题】:Separate groups of objects based on their properties根据对象的属性分隔对象组
【发布时间】:2011-01-07 23:48:10
【问题描述】:

我想根据我的自定义对象的两个属性的值将一个数组分成几个数组。结构如下所示:

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 有一种优雅的方法可以做到这一点,但我不知道从哪里开始。

【问题讨论】:

标签: c# linq


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    我发现这是最简单的方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多