Daniel
Daniel

Reputation: 11054

Working with Anonymous Types with Linq in VB, C#

Say I create two sets of tuples like so:

    Dim losSPResults As List(Of spGetDataResults) = m_dcDataClasses.spGetData.ToList
    Dim loTupleKeys = From t In losSPResults Select t.key1, t.key2

    '' Query on an existing dataset:
    Dim loTupleExistingKeys = from t in m_losSPResults Select t.key3, t.key4

Now I want to perform set operations on these two lists like so:

    Dim loTupleSetDifference = loTupleKeys.Except(loTupleExistingKeys)

Obviously, Linq can't perform a comparator on sets if it doesn't know the sets have uniform definitions, so it will give me this build error:

Option Strict On disallows implicit conversions from 'System.Collections.Generic.IEnumerable(Of < anonymous type>)' to 'System.Collections.Generic.IEnumerable(Of < anonymous type>)'.

How do I work with the declaration of these sets to make them mesh? (Not much luck on google)

[Edit] Still getting the same compile error:

    '*** If we have initialized the list of tools, check to make sure it's up to date
    Dim loTupleDatabaseTools = From tt In lottTorqueTools _
                               Select StationIndex = tt.station_index, SlotNumber = tt.slot_number
    Dim loTupleToolObjects = From tt In m_lottTorqueTools _
                             Select StationIndex = tt.StationIndex, SlotNumber = tt.SlotNumber

    Dim loTupleSetDifference = loTupleDatabaseTools.Except(loTupleToolObjects)

Error is here:

Dim loTupleSetDifference = loTupleDatabaseTools.Except(loTupleToolObjects)

Error 5 Option Strict On disallows implicit conversions from 'System.Collections.Generic.IEnumerable(Of < anonymous type>)' to 'System.Collections.Generic.IEnumerable(Of < anonymous type>)'.

Upvotes: 1

Views: 4388

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499950

If the anonymous types have the same property names with the same types in the same order, they should be the same types (and thus compatible).

EDIT: Based on the comments and the updated question, I suspect the bit you're missing is the ability to name the properties in anonymous types. Change this:

Dim loTupleExistingKeys = from t in m_losSPResults Select t.key3, t.key4

into this:

Dim loTupleExistingKeys = from t in m_losSPResults Select key1=t.key3, key2=t.key4

So long as the types are right, you may then be okay with no more work.

Upvotes: 5

Related Questions