user467384
user467384

Reputation: 1167

How to Group by values in IEnumerable Property

I have a class that looks like this

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

I have a List of TestCase objects that I'd like to be able to group by Categories, such that if a TestCase has the values "a" and "b" in Categories that the instance of that test case would be in the grouping for "a" and the grouping for "b". My understanding of Linq's GroupBy leads me to believe that it would use IEnumerable's Equals method and I'd get an entirely different group for each of my test cases if I grouped by Categories.

I have a brute force solution that achieves the grouping I want

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

but this is ugly. Is there a better way to get the grouping I want?

Upvotes: 4

Views: 13715

Answers (2)

dtb
dtb

Reputation: 217233

If you use the following LINQ query:

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

for a set of TestCase objects like these:

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

then you get the TestCase objects for each distinct category as follows:

Category "A": TestCases "X"
Category "B": TestCases "X", "Y"
Category "C": TestCases "X", "Y"
Category "D": TestCases "Y"

Upvotes: 5

hungryMind
hungryMind

Reputation: 6999

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

Upvotes: 3

Related Questions