2011-08-17 16 views
3

我有一个类,看起来像这样如何通过集团在IEnumerable的值属性

public class TestCase 
{ 
    public IEnumerable<string> Categories { get; private set; } 
} 

我的TestCase对象的列表,我希望能够按类别,例如,如果TestCase在类别中具有值“a”和“b”,该测试用例的实例将在“a”分组和“b”分组中。我对Linq的GroupBy的理解让我相信它会使用IEnumerable的Equals方法,并且如果按类别分组,我会针对每个测试用例获得完全不同的组。

我有一个蛮力解决方案,实现了分组我想

var categoryGroups = new Dictionary<string, List<TestCase>>(); 

foreach (var testCase in testPackage.TestCase) 
{ 
    foreach (var category in testCase.Categories) 
    { 
     if (!categoryGroups.ContainsKey(category)) 
     { 
      categoryGroups.Add(category, new List<TestCase>()); 
     } 

     categoryGroups[category].Add(testCase); 
    } 
} 

但是这是丑陋的。有没有更好的方法来获得我想要的分组?

+3

为什么不使用按功能分组LINQ? – hungryMind

回答

5

如果您使用以下LINQ查询:

var result = from testCase in testCases 
      from category in testCase.Categories 
      group testCase by category into g 
      select g; 

一组的TestCase的对象这样的:

TestCase "X": Categories "A", "B", "C" 
TestCase "Y": Categories "C", "B", "D" 

那么你得到的每一个不同类别的TestCase的对象如下:

Category "A": TestCases "X" 
Category "B": TestCases "X", "Y" 
Category "C": TestCases "X", "Y" 
Category "D": TestCases "Y" 
3
public class TestPackage 
{ 
    public List<TestCase> testCase = new List<TestCase>(); 
} 

public class TestCase 
{ 
    public IEnumerable<string> Categories { get; private set; } 
} 

TestPackage testpackage = new TestPackage(); 
var result = testpackage.testCase.GroupBy(rs => rs.Categories);