在LINQ中翻转分组

时间:2013-10-17 14:17:34

标签: c# linq

我的情况是这样的: 我有一个TFS更改集列表。 每个更改集都有一个ID和相关工作项列表。 工作项具有ID和链接列表,这些链接基本上是具有更改集ID的字符串。

我希望有一个反向层次结构的列表,这意味着,我想要一个工作项列表,并为每个工作项列出相关的变更集(并保留两者的ID字段)。

现在的结构:

---chageset1
       |
       |-------workitem1
       |-------workitem2
---chageset2
       |
       |-------workitem2
       |-------workitem3

我想要的结构

---workitem1
       |
       |-------chageset1
---workitem2
       |
       |-------chageset1
       |-------chageset2
---workitem3
       |
       |-------chageset2

3 个答案:

答案 0 :(得分:2)

WorkItem w1 = new WorkItem { Name = "w1" };
WorkItem w2 = new WorkItem { Name = "w2" };
WorkItem w3 = new WorkItem { Name = "w3" };
ChangeSet c1 = new ChangeSet { Name = "c1", WorkItems = new List<WorkItem> { w1 } };
ChangeSet c2 = new ChangeSet { Name = "c2", WorkItems = new List<WorkItem> { w3, w2 } };
ChangeSet c3 = new ChangeSet { Name = "c3", WorkItems = new List<WorkItem> { w3 } };
List<ChangeSet> changeSets = new List<ChangeSet> { c1, c2, c3 };
var result = changeSets
    .SelectMany(c => c.WorkItems)
    .Distinct()
    .ToDictionary(w => w,
                  w => changeSets.Where(c => c.WorkItems.Contains(w)));
foreach (var kvp in result)
{
    var workItem = kvp.Key;
    var changeSetsForWi = kvp.Value;
    Console.WriteLine(workItem.Name);
    foreach (var cs in changeSetsForWi)
    {
        Console.WriteLine("  " + cs.Name);
    }
}

答案 1 :(得分:2)

你可以用linq来做这件事....

changesets.SelectMany(x => x.workitems.Select(y => new {
                                                         changeset = x.id,
                                                         workitem=y.id})
          .GroupBy(x => x.workitem)
          .Select(x => new {
                              workitem = x.Key, 
                              Changesets = x.Select(y = > y.changeset).ToArray()
                           }).ToArray();

答案 2 :(得分:0)

public class ChangeSet
{
  IList<WorkItem> WorkItems {get;set;};
}

public class WorkItem
{
  IList<ChangeSet> ChangeSets{get;set;};
}

然后执行这两项操作相当容易,迭代您的更改集或工作项并打印出其内容。

foreach(var workitem in workItems)
{
  WriteOut(workItem);
  WriteOut(workItem.ChangeSets);
}