TheIronCheek TheIronCheek - 6 months ago 57
Vb.net Question

VB.NET - Split array of objects into smaller arrays based on value

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
?

Answer

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(0).Type) 

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