Maxime
Maxime

Reputation: 1345

Group elements based on two parameters

I have a list of objects, with two parameters, param1, and param2, defined by this class:

Class test
    public name
    Public param1
    Public param2
End Class

The aim is to group all objects with the same param1 and param2, for further processing.

I have tried to do it using LINQ, and the groupBy feature, but I can't make it work, despite my best efforts.

I have copied my work in a fiddle for clarity: https://dotnetfiddle.net/n19PRv

The expected output is:

num0 (-> num1 is in the same group, it is not displayed)
num2
num3
num4

Thank you for your help,

Upvotes: 2

Views: 54

Answers (2)

Slai
Slai

Reputation: 22876

The correct syntax for comparable anonymous types is

New With { Key .param1 = c.param1, Key .param2 = c.param2 }

where Key is added in front of all properties that are compared. A bit easier with Tuple:

For Each myGroup In list.ToLookup(Function(c) Tuple.Create(c.param1, c.param2))

(GroupBy uses LookUp to get the groups)

Upvotes: 2

Markus
Markus

Reputation: 22491

When using VB.NET, you need to tell the compiler which properties of the anonymous type are used when comparing for equality:

The Key keyword enables you to specify behavior for properties of anonymous types. Only properties you designate as key properties participate in tests of equality between anonymous type instances, or calculation of hash code values. The values of key properties cannot be changed.

See this link for details.

In order to make your sample work, you only need to add the Key keyword in front of the properties of the anonymous type:

From c In list Group c _
By Key = New With { Key c.param1, Key c.param2} Into Group select group

Upvotes: 0

Related Questions