1

I have an array of type Material that I want to split into smaller groups. A Material is an object composed of a Type, Description, and Value. I want to display the materials' Description and Value grouped together by Type so that I can display them sort of like this:

For Each matTypeGroup As Material() In matTypeGroups
    DisplayTypeName(matTypeGroup(0).Type) 

    For Each mat As Material In matTypeGroup
        DisplayMaterialInfo(mat.Description, mat.Value) 
    Next
Next

The final output would look something like this:

- Type1
    Description1: Value1
    Description2: Value2
    Description3: Value3
- Type2
    Description4: Value4
- Type3
    Description5: Value5
    Description6: Value6

How do I split the Material array into an array of Material arrays grouped by Type?

0

1 Answer 1

3

You can use GroupBy:

Dim matTypeGroups = materials.GroupBy(Function(m) m.Type)

You just need to edit your code to work with IGrouping instead of arrays. I assumed the Type is a string here.

For Each matTypeGroup As IGrouping(Of String, Material) In matTypeGroups
    DisplayTypeName(matTypeGroup.Key) 

    For Each mat As Material In matTypeGroup
        DisplayMaterialInfo(mat.Description, mat.Value) 
    Next
Next
Sign up to request clarification or add additional context in comments.

3 Comments

That was going to be my answer as well. While this answer won't return an Array it will group it the way you want. If you need to know how to use it look up IGrouping on the MSDN.
Couldn't you call .ToList() and still work with it like an array - using items in the List by index.
You could but in this case working with the IGrouping directly works just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.