开发者

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?


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"


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜