Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Group by values in IEnumerable Property

Tags:

c#

linq

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?

like image 798
user467384 Avatar asked Feb 23 '23 06:02

user467384


2 Answers

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"
like image 65
dtb Avatar answered Mar 02 '23 21:03

dtb


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);
like image 26
hungryMind Avatar answered Mar 02 '23 21:03

hungryMind