Pass additional data to JsonConverter - vb.net

I deserialize object where one of the properties is a foreign key (eg an identity value from a database table). During deserialization I would like to use a JsonConverter to retrieve the corresponding object from a collection.
I know how to write a use custom JsonConverters. I don't know how to pass the collection to the JsonConverter, because the converter is specified at design time (like below), but the collection obviously only exists at runtime:
<JsonConverter(GetType(JSonCustomConverter))>
Public Property SomeProperty As SomePropertyClass
So the JSonCustomConverter's ReadJson should look this:
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
If reader.Value Is Nothing Then Return False
Dim value As String = reader.Value.ToString().Trim()
retun MagicallyGetMyCollectionValue(value)
End Function
So the silly function name MagicallyGetMyCollectionValue is just a placeholder to show you where I am stuck. I don't want to access the collection through a global variable, but I don't know how to pass the collection to the ReadJson either.
I would be happy, if someone could point me in the right direction.
Edit: Let me try to give a better example.
Suppose I have the following class:
class ParentObject
<JssonConverter(GetType(JsonCustomConverter))>
Property SomeProperty As SomePropertyClass
end class
I would deserialize my json data like this:
dim result = JsonConvert.DeserializeObject(jsonData, GetType(ParentObject))
Now assume, that the json data doesn't contain the complete representation of an instance of the SomePropertyClass, but only a key value e.g. an key as string. Suppose I have a collection like this:
dim cache as Dictionary(of string, SomePropertyClass)
That cache shall contain all the instances that I need. So my JSonCustomConverter should have a ReadJson Function like this:
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
If reader.Value Is Nothing Then Return nothing
Dim value As String = reader.Value.ToString().Trim()
Dim cachedObject as SomePropertyClass = nothing
if cache.TryGetValue(value, cachedObject) then return cachedObject
retun Nothing ' or new SomePropertyClass(value)
End Function
So I want the ReadJson to lookup the instance based on the key value.
How would I pass the cache-Dictionary into the ReadJson function? I could use a singelton class that contains the cache an som getInstance-method to retrieve it, but I wouldn't want to do this.

You can pass additional data to your custom JsonConverter using StreamingContext.Context via JsonSerializer.Context. Using this mechanism it becomes possible to map class instances to names in a generic manner.
First, define the following interfaces and generic converter:
Public Interface ISerializationContext
Function TryGetNameTable(Of T)(ByRef table as INameTable(Of T)) as Boolean
End Interface
Public Interface INameTable(Of T)
Function TryGetName(value As T, ByRef name as String) As Boolean
Function TryGetValue(name as String, ByRef value as T) As Boolean
End Interface
Public Class NameTable(Of T) : Implements INameTable(Of T)
Public Property Dictionary as Dictionary(Of String, T) = New Dictionary(Of String, T)()
Public Property ReverseDictionary as Dictionary(Of T, String) = New Dictionary(Of T, String)()
Public Function Add(value as T, name as String) as T
Dictionary.Add(name, value)
ReverseDictionary.Add(value, name)
Return value
End Function
Public Function TryGetName(value As T, ByRef name as String) As Boolean Implements INameTable(Of T).TryGetName
Return ReverseDictionary.TryGetValue(value, name)
End Function
Function TryGetValue(name as String, ByRef value as T) As Boolean Implements INameTable(Of T).TryGetValue
Return Dictionary.TryGetValue(name, value)
End Function
End Class
Public Class ObjectToNameConverter(Of T)
Inherits JsonConverter
Public Overrides Function CanConvert(objectType As Type) As Boolean
Return GetType(T) = objectType
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Dim tValue = CType(value, T)
Dim context as ISerializationContext = CType(serializer.Context.Context, ISerializationContext)
If context Is Nothing
Throw New JsonSerializationException("No ISerializationContext.")
End If
Dim nameTable as INameTable(Of T) = Nothing
If (Not context.TryGetNameTable(Of T)(nameTable))
Throw New JsonSerializationException("No NameTable.")
End If
Dim name as String = Nothing
if (Not nameTable.TryGetName(tValue, name))
Throw New JsonSerializationException("No Name.")
End If
writer.WriteValue(name)
End Sub
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim context as ISerializationContext = CType(serializer.Context.Context, ISerializationContext)
If context Is Nothing
Throw New JsonSerializationException("No ISerializationContext.")
End If
Dim nameTable as INameTable(Of T) = Nothing
If (Not context.TryGetNameTable(Of T)(nameTable))
Throw New JsonSerializationException("No NameTable.")
End If
Dim name As String = serializer.Deserialize(Of String)(reader)
If name Is Nothing Then
Return Nothing
End If
dim tValue as T = Nothing
nameTable.TryGetValue(name, tValue)
return tValue
End Function
End Class
Next, define the following concrete implementations:
Public Class RootObject
<JsonConverter(GetType(ObjectToNameConverter(Of SomePropertyClass)))> _
Public Property SomeProperty As SomePropertyClass
End Class
Public Class SomePropertyClass
End Class
Public Class MySerializationContext : Implements ISerializationContext
Public Function Add(value as SomePropertyClass, name as String) as SomePropertyClass
Return SomePropertyNameTable.Add(value, name)
End Function
Property SomePropertyNameTable as NameTable(Of SomePropertyClass) = New NameTable(Of SomePropertyClass)
Public Function TryGetNameTable(Of T)(ByRef table as INameTable(Of T)) as Boolean Implements ISerializationContext.TryGetNameTable
if (GetType(T) Is GetType(SomePropertyClass))
table = SomePropertyNameTable
return True
End If
table = Nothing
return False
End Function
End Class
Now, you can replace instances of SomePropertyClass with their names during deserialization as follows:
Dim context as MySerializationContext = New MySerializationContext()
Dim someProperty as SomePropertyClass = context.Add(New SomePropertyClass(), "My Name")
Dim root as RootObject = New RootObject With { .SomeProperty = someProperty }
Dim settings = new JsonSerializerSettings With _
{ _
.Context = New System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.All, context)
}
Dim json as String = JsonConvert.SerializeObject(root, settings)
Console.WriteLine(json) ' Prints {"SomeProperty":"My Name"}
dim root2 as RootObject = JsonConvert.DeserializeObject(Of RootObject)(json, settings)
' Assert that the same instance of SomeProperty was used during deserialization
Assert.IsTrue(root2.SomeProperty Is root.SomeProperty)
Assert.IsTrue(json.Equals("{""SomeProperty"":""My Name""}"))
Notes:
ISerializationContext.TryGetNameTable(Of T)(ByRef table as INameTable(Of T)) is generic so that object-to-name replacement can be supported for multiple types of objects simultaneously without the converters interfering with each other.
The concrete implementation need not be so generic, however. Here MySerializationContext only supports name replacement for instances of SomePropertyClass. Others could be added as needed.
As stated in Does Json.NET cache types' serialization information?, Newtonsoft recommends caching instances of DefaultContractResolver and its subtypes for best performance. Thus it may be preferable to pass additional data via StreamingContext.Context rather than via freshly allocated instances of subclasses of DefaultContractResolver.
Sample working .Net fiddle #1 here.
As an alternative, while the design above works, in my opinion it would be simpler to remove <JsonConverter(GetType(ObjectToNameConverter(Of SomePropertyClass)))> from SomeProperty and instead pass an appropriately initialized ObjectToNameConverter(Of SomePropertyClass), containing a local reference to some INameTable(Of SomePropertyClass), in JsonSerializerSettings.Converters.
Define the converter and interfaces like so. Notice that ObjectToNameConverter(Of T) now has a parameterized constructor and that ISerializationContext is no longer required:
Public Interface INameTable(Of T)
Function TryGetName(value As T, ByRef name as String) As Boolean
Function TryGetValue(name as String, ByRef value as T) As Boolean
End Interface
Public Class NameTable(Of T) : Implements INameTable(Of T)
Public Property Dictionary as Dictionary(Of String, T) = New Dictionary(Of String, T)()
Public Property ReverseDictionary as Dictionary(Of T, String) = New Dictionary(Of T, String)()
Public Function Add(value as T, name as String) as T
Dictionary.Add(name, value)
ReverseDictionary.Add(value, name)
Return value
End Function
Public Function TryGetName(value As T, ByRef name as String) As Boolean Implements INameTable(Of T).TryGetName
Return ReverseDictionary.TryGetValue(value, name)
End Function
Function TryGetValue(name as String, ByRef value as T) As Boolean Implements INameTable(Of T).TryGetValue
Return Dictionary.TryGetValue(name, value)
End Function
End Class
Public Class ObjectToNameConverter(Of T)
Inherits JsonConverter
Private Property NameTable as INameTable(Of T)
Public Sub New(nameTable as INameTable(Of T))
If nameTable Is Nothing
Throw new ArgumentNullException("nameTable")
End If
Me.NameTable = nameTable
End Sub
Public Overrides Function CanConvert(objectType As Type) As Boolean
Return GetType(T) = objectType
End Function
Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
Dim tValue = CType(value, T)
Dim name as String = Nothing
if (Not NameTable.TryGetName(tValue, name))
Throw New JsonSerializationException("No Name.")
End If
writer.WriteValue(name)
End Sub
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim name As String = serializer.Deserialize(Of String)(reader)
If name Is Nothing Then
Return Nothing
End If
dim tValue as T = Nothing
NameTable.TryGetValue(name, tValue)
return tValue
End Function
End Class
Then serialize as follows:
dim nameTable = new NameTable(Of SomePropertyClass)()
Dim someProperty as SomePropertyClass = nameTable.Add(New SomePropertyClass(), "My Name")
Dim root as RootObject = New RootObject With { .SomeProperty = someProperty }
Dim settings = new JsonSerializerSettings()
settings.Converters.Add(new ObjectToNameConverter(Of SomePropertyClass)(nameTable))
Dim json as String = JsonConvert.SerializeObject(root, settings)
Console.WriteLine(json) ' Prints {"SomeProperty":"My Name"}
dim root2 as RootObject = JsonConvert.DeserializeObject(Of RootObject)(json, settings)
' Assert that the same instance of SomeProperty was used during deserialization
Assert.IsTrue(root2.SomeProperty Is root.SomeProperty)
Assert.IsTrue(json.Equals("{""SomeProperty"":""My Name""}"))
Doing things this way eliminates the dependence of static serialization methods on runtime code that is present in the first solution. Now all name replacement logic is handled in runtime in one location.
Sample fiddle #2 here.

As requested by #doom87er I will share the code, that worked for me. The solution is based on the comment by #dbc, with some changes. Please treat below code more like a conceptual code: I had to change some of the names and leave out some logik, that isn't required for this proof of concept. So there might be typos in it.
The main solution is to subclass the DefaultContractResolver and add the the cache-dictionary to that class. Something like this:
Public Class CacheContractResolver
Inherits DefaultContractResolver
Public Cache As Dictionary(of string, SomePropertyClass)
Public Sub New(preFilledCache As Dictionary(of string, SomePropertyClass)
Me.Cache = preFilledCache
End Sub
End Class
Then you pass the custom contract resolver using the JsonSerializerSettings like this:
Dim settings = New JsonSerializerSettings
settings.ContractResolver = New SupportControllerContractResolver(prefilledCache)
Dim result = JsonConvert.DeserializeObject(Of ParentObject)(jsonData, settings)
where prefilledCache is an instance of a dictionary containing the SomePropertyClass-objects.
The last step is to retrieve the cache in my JsonConverter's ReadJson function (that I attached to the SomeProperty as shown in the original post's sample code):
Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
Dim cacheResolver = TryCast(serializer.ContractResolver, CacheContractResolver)
if cacheResolver is nothing return nothing ' add some better null handling here
Dim value As String = reader.Value.ToString().Trim()
Dim cachedObject as SomePropertyClass = nothing
if cacheResolver.Cache.TryGetValue(value, cachedObject) then return cachedObject
retun Nothing ' or new SomePropertyClass(value)
End Function
I tried it and it seems to work.
So in a nut shell:
Subclass the DefaultContractResolver and include all the additional data, that you need.
Pass an instance of you custom contract resolver with the additional data in the JsonSerializerSettings.
In your JsonConverter trycast the passed contract resolver back to your custom contract resolver and there you have your additional data.
I would be happy if you comment on any catches that I might miss, but I think this should be solution that I can live with.
Thanks for you coments and help.
Sascha

Related

Create Custom Class Dynamically

I am working on a project where I need to create a multitude of custom classes to interact properly with an API (While I know there might be questions on why, and such, but the short is it has to be this way).
Is there a way to create a complete custom class dynamically on the fly? So instead of
class person
Private _Height
Property Height As Integer
Get
Return _Height
End Get
Set(value As Integer)
_Height = value
End Set
End Property
'Continue for all properties of person
I would like to be able to create a new object and through other input create this dynamically.
dim NewClass as object
dim NewProperty as property
NewProperty.name="Height"
NewProperty.datatype=string
NewClass.AddProperty(NewProperty)
Is this possible? It would save me a lot of time if it is.
I don't like late binding but there are options (I like my option strict on). Like using the DynamicObject or the ExpandoObject class. Your question is vague so I have no idea if it can work.
Sub Main()
Dim test As Object = New SampleDynamicClass()
test.SomeProperty = "123"
Console.WriteLine(test.SomeProperty)
Console.ReadLine()
End Sub
Public Class SampleDynamicClass
Inherits DynamicObject
Private _values As New Dictionary(Of String, String)
Public Sub New()
End Sub
Public Function GetPropertyValue(ByVal propertyName As String) As String
Return _values(propertyName)
End Function
Public Function SetPropertyValue(ByVal propertyName As String, ByVal value As Object) As Boolean
If _values.ContainsKey(propertyName) Then
_values(propertyName) = value.ToString()
Else
_values.Add(propertyName, value.ToString())
End If
Return True
End Function
Public Overrides Function TryGetMember(ByVal binder As GetMemberBinder,
ByRef result As Object) As Boolean
result = GetPropertyValue(binder.Name)
Return If(result Is Nothing, False, True)
End Function
Public Overrides Function TryInvokeMember(ByVal binder As InvokeMemberBinder,
ByVal args() As Object,
ByRef result As Object) As Boolean
result = GetPropertyValue(binder.Name)
Return If(result Is Nothing, False, True)
End Function
Public Overrides Function TrySetMember(binder As SetMemberBinder, value As Object) As Boolean
Return SetPropertyValue(binder.Name, value)
End Function
Dim person = New With {Key .Height = 12}
Dim personTypes = New With {Key .Happy = 1, .Sad = 2}
Dim personsAndTypes = New With {Key .Person = person, .Type = personTypes}
The question is kind of vague, but if you have no need for other fields and methods, or reuse Anonymous Types

Bind a detail report to a class model with properties stored in a Dictionary (VB.NET, Devexpress)

I'm trying the example from Devexpress
Dim binding As New XRBinding("Text", dsProducts1, "Products.UnitPrice")
But my models does not have their properties explicitly written in their class. It would take a method GetProperty("column_name_here") to get it's data. I'm wondering if the 3rd parameter of XRBinding can be a method? Like:
Dim binding As New XRBinding("Text", dsProducts1, product.GetProperty("name"))
Additional Info:
All of my model classes extends this Dao class which is responsible in getting data in the database. The Dao class have a protected variable as a Dictionary(Of String, Object) to store the values (key = column name, value = column row value) from the database.
Now when I want to get something in the database, I only call
Dim user As New User // this class extends the Dao class
Dim userId = user.GetProperty("id") // Method to get the value from Dictionary, first parameter is the Dictionary key or column name from the DB
I made this so that I wont have to create every model class and set the properties of that class, as it is kinda cumbersome.
It seems that there are no way to bind to some method. I suggest you to take a look at ExpandoObject dynamic class. The members of this class can be added at runtime. This class implements IDictionary(Of String, Object) interface which you can use to generate properties from your Dictionary(Of String, Object).
Here is example:
Example of base Dao class implementation with protected Dictionary(Of String, Object) property:
Public Class Dao
Private _values As Dictionary(Of String, Object)
Public Sub New()
_values = New Dictionary(Of String, Object)
End Sub
Public Overridable Sub Fill(index As Integer)
_values.Clear()
_values.Add("ID", index)
_values.Add("Product", "Banana " & index)
_values.Add("Price", 123.45 + index)
End Sub
Protected ReadOnly Property Values As Dictionary(Of String, Object)
Get
Return _values
End Get
End Property
End Class
Example of Dao class descendant with DynamicValues property which returns ExpandoObject based on Dictionary(Of String, Object) (you must omit the type of property):
Public Class DynamicDao
Inherits Dao
Private _dynamicValues As ExpandoObject
Public Overrides Sub Fill(index As Integer)
MyBase.Fill(index)
_dynamicValues = New ExpandoObject()
Dim keyValues = DirectCast(_dynamicValues, IDictionary(Of String, Object))
For Each pair In Values
keyValues.Add(New KeyValuePair(Of String, Object)(pair.Key, pair.Value))
Next
End Sub
Public ReadOnly Property DynamicValues ' <= There is no type. In hint is displayed «As Object».
Get
Return _dynamicValues
End Get
End Property
End Class
Usage of DynamicDao class in XtraReport:
Dim list = New List(Of DynamicDao)
For index% = 0 To 9
Dim dao = New DynamicDao()
dao.Fill(index%)
list.Add(dao)
Next
Dim labelID = New XRLabel()
labelID.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.ID"))
Dim labelProduct = New XRLabel()
labelProduct.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.Product"))
labelProduct.LeftF = 50
Dim labelPrice = New XRLabel()
labelPrice.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.Price"))
labelPrice.LeftF = 150
Dim detail = New DetailBand()
detail.Controls.Add(labelID)
detail.Controls.Add(labelProduct)
detail.Controls.Add(labelPrice)
Dim report = New XtraReport()
report.Bands.Add(detail)
report.DataSource = list
report.ShowRibbonPreview()

Can a class's properties be assigned using a lookup, or must each property be assigned individually?

VS2013, Visual Basic
I have a class with many properties.
Public Class
Property 1
.
.
Property N
End Class
I have a list of name value pairs
name1, value1
.
.
nameN, valueN
The values in the name value pairs will be assigned to the property values.
Does VB have a way that allows me to take one of the names and use it to 'look up' the class property, select it an assign the value to it, looping through the name-value pairs to make all the assignments?
I didn't see a method attached to my Class as I defined it. Should I define my Class differently? I used the Class in the EF6 Code First method to create the backing database.
The alternative as I see it is to list each Class property one by one, looking up the name and assign the value, but that seems like a tedious way of doing things.
Just thought I would ask. Maybe there's a better way to do this.
Thanks.
Best Regards,
Alan
There are three classes which will help you; TypeDescriptor, PropertyDescriptor and PropertyDescriptorCollection. They are all located in the System.ComponentModel namespace.
Imports System.ComponentModel
We'll be using the following class for this example:
Public Class Foo
'Implements ICustomTypeDescriptor (Optional)
Public Property A() As String
Public Property B() As Date
Public Property C() As Integer
Public Property D() As Boolean
Public Overrides Function ToString() As String
Return String.Format("A='{0}', B='{1}', C='{2}', D='{3}'", Me.A, Me.B, Me.C, Me.D)
End Function
End Class
Get all the properties by invoking the static method GetProperties of the TypeDescriptor class. It returns a collection of PropertyDescriptor classes - your properties. Then you simply invoke either the SetValue and/or GetValue methods. Note that you can implement a custom type descriptor by implementing the ICustomTypeDescriptor interface.
Private Sub RunTest()
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(Foo))
Dim ignoreCase As Boolean = True
Dim foo1 As New Foo()
properties.Find("A", ignoreCase).SetValue(foo1, "hello")
properties.Find("B", ignoreCase).SetValue(foo1, Date.Now)
properties.Find("C", ignoreCase).SetValue(foo1, 1234I)
properties.Find("D", ignoreCase).SetValue(foo1, True)
'Get property value:
'Dim a As String = CType(properties.Find("A", ignoreCase).GetValue(foo1), String)
Debug.WriteLine(foo1.ToString())
End Sub
Output: (immediate window)
A='hello', B='30.11.2014 11:14:39', C='1234', D='True'
Extension
To expand this even further one can create some extension methods.
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()>
Public Function GetProperty(Of TComponent)(component As TComponent, propertyName As String, Optional ByVal ignoreCase As Boolean = True) As Object
Return TypeDescriptor.GetProperties(GetType(TComponent)).Find(propertyName, ignoreCase).GetValue(component)
End Function
<Extension()>
Public Function GetProperty(Of TComponent, TValue)(component As TComponent, propertyName As String, Optional ByVal ignoreCase As Boolean = True) As TValue
Return CType(TypeDescriptor.GetProperties(GetType(TComponent)).Find(propertyName, ignoreCase).GetValue(component), TValue)
End Function
<Extension()>
Public Sub SetProperty(Of TComponent)(instance As TComponent, propertyName As String, value As Object, Optional ByVal ignoreCase As Boolean = True)
TypeDescriptor.GetProperties(GetType(TComponent)).Find(propertyName, ignoreCase).SetValue(instance, value)
End Sub
End Module
Now it's very easy to set/get a property value by name.
Private Sub RunTest()
Dim foo1 As New Foo()
foo1.SetProperty("A", "hello")
foo1.SetProperty("B", Date.Now)
foo1.SetProperty("C", 1234I)
foo1.SetProperty("D", True)
'Get property value:
'Dim a As String = CType(foo1.GetProperty("A"), String)
'Dim a As String = foo1.GetProperty(Of String)("B")
Debug.WriteLine(foo1.ToString())
End Sub
Output:
A='hello', B='30.11.2014 11:18:17', C='1234', D='True'

Enforce that .Equals override must compare newly-added properties

I have a class that overrides Equals. This class has many properties, and more properties will be added in the future. How can I enforce that, when new properties are added, the Equals override must be changed to consider those properties?
I have a partial solution, so you can see what I'm trying to do:
Public Class LotsOfProperties
Public Shared ReadOnly properties As New HashSet(Of String) From {"propertyA", "propertyB"}
Public Property propertyA As String
Public Property propertyB As List(Of String)
Public Overloads Function Equals(ByVal otherObj As LotsOfProperties) As Boolean
Dim differences As New List(Of String)
For Each propertyName As String In properties
Dim meValue As Object = getValueByPropertyName(Me, propertyName)
Dim otherObjValue As Object = getValueByPropertyName(otherObj, propertyName)
If Not meValue.Equals(otherObjValue) Then
differences.Add(propertyName)
End If
Next
Return (differences.Count = 0)
End Function
Private Function getValueByPropertyName(ByVal obj As Object, ByVal name As String) As Object
Dim rtnObj As Object
Dim pInfo As Reflection.PropertyInfo = obj.GetType.GetProperty(name)
rtnObj = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
Return rtnObj
End Function
End Class
However, this won't work because I want to use SequenceEqual to compare the List property but not to compare the String property. Because I have to use different methods to test equality of each property, I can't just loop through the properties with reflection.
This seems like a common use-case. Is there a simple solution, or do I need to simply trust that future developers will modify Equals when adding new properties?

Casting substrings with linq into a list of object and than sorting it base on property in vb.net

This have to be in vb.net linq, i'm pretty sure I could do it in c#, but I cant find any good enough translator to help me ... even the answers I find here in SO seems to only be written in linq, hence the question which might be a duplicate of a c# one.
That being said, considering these 2 classes :
Public class User
Public Property Name() As String
Public Property Teams As TeamList
Public sub New(d as string, results as TeamList)
me.name = d
me.Teams = results
end sub
end class
Public Class TeamList
Public Property TeamName() As String
Public Property fullscore() As list(of object)
Public sub New(name as string, value as list(of string))
me.TeamName = name
me.fullscore = value
me.fullscore = getFullScore(value) (return a list of object)
end sub
End Class
I'm struggling in the final steps of my linq -to - object : (you can copy /paste this in linqpad)
Sub Main
dim Definition as new Dictionary(of String, object)
definition.add("user1_redTeam-02", new object)
definition.add("user1_redTeam-01", new object)
definition.add("user1_blueTeam-03", new object)
definition.add("user2_redTeam-01", new object)
definition.add("user1_redTeam-03", new object)
definition.add("user1_blueTeam-01",new object)
definition.add("user2_blueTeam-01", new object)
definition.add("user1_blueTeam-02", new object)
definition.add("user2_redTeam-02", new object)
Dim q3 = (From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_")(0)) _
Select New With _
{.UserName = userlists.Key, _
.animationList = (From scList In userlists.GroupBy(Of String)(Function(s) s.Split("-")(0)) _
Select New With {.Team = scList.Key, _
.Score = scList.ToList()})})
q3.dump()
End Sub
this is the result :
now, all I want is to sort the .score attribute (just a simple .sort(), and instead of returning an anonymous q3 object, which I,m cluless to transform, I'd like the q3 to be a list(of User)
it think it should looks like this ... but I cant make it works, i always gets some linq conversion errors :
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Linq.IGrouping2[System.String,System.String],UserQuery+User]' to type 'System.Collections.Generic.List`1[UserQuery+User]'.
Dim q3 as List(of User)= (From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_")(0)) _
Select New User(userlists.Key, (From scList In userlists.GroupBy(Of String)(Function(s) s.Split("-")(0)) _
Select New TeamList(scList.Key, scList.ToList()))))
Your code examples seem to be incorrect - for example, it seems like User.Teams should be a list of some type, not a TeamList object, which isn't really a list. Anyway, with a little modification, this is what I came up with - maybe it's close to what you were looking for (a list of users with the scores sorted). You can paste into LINQPad to run it.
Sub Main
Dim Definition As New Dictionary(of String, Object)
definition.add("user1_redTeam-02", New Object)
definition.add("user1_redTeam-01", New Object)
definition.add("user1_blueTeam-03", New Object)
definition.add("user2_redTeam-01", New Object)
definition.add("user1_redTeam-03", New Object)
definition.add("user1_blueTeam-01",New Object)
definition.add("user2_blueTeam-01", New Object)
definition.add("user1_blueTeam-02", New Object)
definition.add("user2_redTeam-02", New Object)
Dim q3 = (
From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_"c)(0))
Select New User(
userlists.Key,
(From scList In userlists.GroupBy(Function(s) s.Split("-"c)(0))
Select New Team(scList.Key.Split("_"c)(1), scList.OrderBy(Function(s) s).ToList())).ToList()
)
).ToList()
q3.dump()
End Sub
' Define other methods and classes here
Public class User
Public Property Name() As String
Public Property Teams() As List(Of Team)
Public Sub New(d As String, results As List(Of Team))
Me.Name = d
Me.Teams = results
End Sub
End Class
Public Class Team
Public Property TeamName() As String
Public Property FullScore() As List(Of String)
Public Sub New(name As String, value As List(Of String))
Me.TeamName = name
Me.FullScore = value
End Sub
End Class