How can I sort some objects depending on one of their properties - vb.net

I want to sort a number of objects in certain order (ascending or descending) depending on one of their properties. I learned that interfaces can help doing this but can't figure out how to do this.
I am going to figure out what I want to do
I'll try to shorten my code to only touch the problem
Public class Course
Public property priority as integer
Public property code as string
Public sub new (byval a as integer,
byval b as string)
End sub
End class
Module module1
Public sub main ()
Dim a as new course(3,"ECE333")
Dim b as new course (5,"ECE332")
Dim c() = {a,b}
End sub
End module
So I want to sort the course objects at c descending order according to their priority

This is the best I can do for you until we have more information about the items in your question:
Dim sorted = items.OrderBy(Function(i) i.Property)

Use the List.sort method. You will have to provide a Comparator method to do the comparison.
Say, if your list is called myList and it has a property called height and you want to sort by height.
You can do the following:
myList.Sort(Function(a, b) a.height.CompareTo(b.height))

Related

How can I assign a value to a number of different variables in a collection using loops?

I have a problem that has been bugging me for a while now. Consider this code:
Public Class Class1
Dim VariableList as New List(of Object) From {MainForm.X, MainForm.Y,
SettingsForm.Z, SettingsForm.Textbox1.Text} '...etc.
Sub SetToZero()
For Each Element in VariableList
Element = 0
Next
End Sub
Sub SetToCustomValue(value As Double)
For Each Element in VariableList
Element = value
Next
End Sub
Sub LoadValuesFromFile()
Dim path As String = MainForm.GetPath()
For Each Element in VariableList
Element = File.Readline()
Next
End Sub
Sub SaveValuesToFile()
Dim path As String = MainForm.GetPath()
For Each Element in VariableList
Element = File.Writeline()
Next
End Sub
'and more similar functions/subs
As you can see, what this class does is that it takes lot of different variables from different places into a collection, and then various functions read or write values to every variable in that collection using loops. In this example, I have just a few variables, but most of the time there are dozens.
Reading the values is not a problem. Writing them, is, because when I declare that VariableList at the top of my class, that List just makes a copy of each variable, rather than maintaining a reference to it. Meaning that if, say, one of the functions modifies the MainForm.X in that List, the actual variable MainForm.X is not modified. To work with references, I would have to forgo loops, and assign every single variable manually, in every function. Which is obviously a lot of bad code. I want to declare that list of variables only once, and then use loops, like in this example code that I wrote above. My question is, how can I make such a container (List, Array, whatever) that would retain the references to the original variables in it, and make the code above possible?
There is no easy way to store pointers to variables in VB.NET. As a workaround, you can use a class to store your variables, as a class is always used as a pointer.
Here's an example of a way to achieve this with a ContainerClass which own a Dictionary of integers. One interest of this method would be that you can declare and name "variables" dynamically. In reality, they will be managed KeyValuePair. Once you have instantiated a copy of this class, you can use it to "manage" your variables by using this class as your pointer.
I included a loop which set all the integers to the same number just for fun, and to demonstrate the kind of manipulation which would end up having an effect similar to one of those described in your question.
Public Class Form2
'This is the container class which will be used to bypass the lack of pointers
'if you wanted to change a property, like the window width, it would be more difficult, but simples variables will be no trouble
Private variableContainer As New VariableContainer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
variableContainer.AddVar("X", 5)
variableContainer.AddVar("Y", 15)
Debug.Print(variableContainer.GetVar("X"))
Debug.Print(variableContainer.GetVar("Y"))
variableContainer.SetAllVar(42)
Debug.Print("Next line will print 42")
Debug.Print(variableContainer.GetVar("X"))
End Sub
End Class
Public Class VariableContainer
'I know a public variable wouldn't need the fancy functions down there, but it's usually better to encapsulate, especially if you're working with a team
'and "future you" count as a teammate, never forget that...
Private list As New Dictionary(Of String, Integer)
Public Sub AddVar(ByVal name As String, ByVal value As Integer)
list.Add(name, value)
End Sub
Public Function GetVar(ByVal name As String) As Integer
If list.ContainsKey(name) Then
Return list(name)
Else
'I choose -1 arbitrarily, don't put too much thinking into this detail
Return -1
End If
End Function
Public Sub SetVar(ByVal name As String, ByVal num As Integer)
If list.ContainsKey(name) Then
list(name) = num
End If
End Sub
Public Sub SetAllVar(ByVal num As Integer)
Dim dict As New Dictionary(Of String, Integer)
For Each item As KeyValuePair(Of String, Integer) In list
dict.Add(item.Key, num)
Next
list = dict
End Sub
End Class
Have fun!

Save reference to private field (vb.net)

I'm quite new to VB.NET programming and I have this situation:
I have one class Foo with some private fields (the number can be increased so I want to write some flexible code) and its corresponding public readonly properties. For updating the values of the private fields, I have to read them in a OPC server. When I register to an OPCServer item, I get an integer, called ServerHandle, to identify it. Then, when I read the OPC server, I get several ServerHandles with its corresponding values, in the form of a dictionary (serverHandles as keys).
What I would like to create while creating my object, is a list of helper objects (I have called them Item) with only two public fields, ServerHandle and a reference to a private field, so I could do something like this when I get the dictionay of updates values:
Public Class Foo
Private field1 As Double
Private field2 As Double
Private listOfitems As List(Of Item)
Private Sub UpdateValues(dictionaryOfValues As Dictionary(Of Integer, Double))
For Each item As Item In listOfitems
item.Field = dictionaryOfValues(item.ServerHandle)
Next
End Sub
End Class
Public Class Item
Public Field As Object
Public ServerHandle As Integer
End Class
I know it is not possible to save a reference to a private field like this... but I would like to know if there is some way of doing something similar to what I'm trying.
If not... do you have any suggestions about how could I do this? (I have the feeling that I'm complicating my solution needlessly).
Thank you very much!
You need some type of publicly exposed object on your Foo class, I suggest making a read-only public property for the listOfItems, like this:
Public Class Foo
Private field1 As Double
Private field2 As Double
Private listOfitems As List(Of Item)
Public Property ListOfItems() As List(Of Integer)
Get
Return listOfitems
End Get
End Property
Private Sub UpdateValues(dictionaryOfValues As Dictionary(Of Integer, Double))
For Each item As Item In listOfitems
item.Field = dictionaryOfValues(item.ServerHandle)
Next
End Sub
End Class

Setting Up These Types While Keeping It Properly Structured

I'm completely stuck in a situation and I have no idea on where to go from here. I'm creating a very large project, so my goal is to keep the code itself as clean as possible and keeping as many hacks as possible out of the mix.
Here is the situation.
I have a class called Woo_Type, it is the parent of my many derived classes.
Public MustInherit Class Woo_Type
Private Shared TypeList As New Dictionary(Of String, Woo_Type)
Public MustOverride Sub SetValue(ByVal val As Object)
Public MustOverride Function GetValue() As Object
Public Shared Function GetTypeFromName(ByVal name As String) As Woo_Type
Return TypeList(name)
End Function
Public Shared Sub AddType(ByVal name As String, ByVal def As Woo_Type)
TypeList.Add(name, def)
End Sub
End Class
I have many classes that Inherit from Woo_Type that have similar structures to this:
Public Class Woo_tpInt
Inherits Woo_Type
Private value As Integer = 0
Public Overrides Function GetValue() As Object
Return value
End Function
Public Overrides Sub SetValue(val As Object)
value = val
End Sub
End Class
I want to be able to do things like:
Woo_Type.GetTypeFromName("int")
And have it return something like the class or something...
At this point I'm really confused as to what I want and I didn't know if anybody had any suggestions. To make sure that GetTypeFromName worked correctly, I had in an Initializer sub the following:
Public Sub InitializeTypes()
Woo_Type.AddType("int", Woo_tpInt)
Woo_Type.AddType("String", Woo_tpInt)
End Sub
But I quickly realized that-that obviously doesn't work either.
So this may seem confusing but I'm basically wondering how to better structure this so that everything works...
What do you want to do with the result? Are you sure you don't simply need generics?
Public Class WooType(Of T)
Public Property Value As T
End Class
Public Class Test
Public Sub Foo()
Dim int As New WooType(Of Integer)
int.Value = 42
Dim str As New WooType(Of String)
str.Value = "Forty-Two"
End Sub
End Class
If what you want to do is get the type itself (as opposed to an object), I would recommend using reflection rather than trying to reinvent the wheel. For instance, to get the Woo_tpInt type, you could do this:
Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType("WindowsApplication1.Woo_tpInt") ' Change WindowsApplication1 to whatever your namespace is
If you want to use a shorter name like "int" to mean "WindowsApplication1.Woo_tpInt", you could create a dictionary to store the translation table, for instance:
Dim typeNames As New Dictionary(Of String, String)
typeNames.Add("int", GetType(Woo_tpInt).FullName)
Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType(typeNames("int"))

VB Polymorphism Constructors Default and Properties. Similar Class to Listbox

I've been banging my head against a wall for sometime on this one.
I'm trying to create a class for storing data on People with another class to store their Bank Transactions.
Ideally, this all be hidden away and leave only simple statments, declarations and functions available to the programmer. These will include:
Dim Clients As New ClientList
Clients.Count 'readonly integer
Clients.Add("S")
Clients.Refresh()
Clients(n).Remove()
Clients(n).Transaction.Add()
Clients(n).Transaction(n).Remove()
I know this is possible as these exist in the Listbox Class though can't figure out how it's done.
Any help would be appreciated.
Thanks in advance!
Create a Transaction and a Client class
Public Class Transaction
'TODO: Implement Transaction
End Class
Public Class Client
Public ReadOnly Transactions As List(Of Transaction) = New List(Of Transaction)
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
Public Name As String
End Class
Create a ClientList class
Public Class ClientList
Inherits List(Of Client)
Public Overloads Sub Add(ByVal name As String)
Add(New Client(name))
End Sub
Public Sub Refresh()
' Do what ever you want Refresh to do
End Sub
End Class
You can then use the client list like this
Dim clients As New ClientList
clients.Add("S")
' Or
clients.Add(New Client("T"))
Dim n As Integer = clients.Count
Dim m As Integer = clients(0).Transactions.Count
clients.Refresh()
clients.RemoveAt(5)
clients(n - 1).Transactions.Add(New Transaction())
clients(n - 1).Transactions.RemoveAt(2)
Dim name As String = clients(0).Name
Dim client As Client = clients(0)
Use the generic List(Of T) class, specialized to hold your Client objects. It already provides all of the methods you want without your having to write a single line of code!
So you would first write a Client class that contained all of the properties (data) and methods (actions) relating to a "client":
Public Class Client
Public Property Name As String
Public Property AmountOwned As Decimal
Public Sub Bill()
BillingManager.BillClient(Me)
End Sub
' ... etc.
End Class
Then, you would create the List(Of T) to hold all of your instances of the Client class:
Dim clients As New System.Collections.Generic.List(Of Client)
If, for whatever reason, you needed to specialize the behavior of the Add, Remove, etc. methods provided by the collection class, or add additional methods, you would need to change strategies slightly. Instead of using List(Of T), you would inherit from Collection(Of T) and create a custom collection class like so:
Public Class ClientCollection
Inherits System.Collections.ObjectModel.Collection(Of T)
' ... customize as desired ...
End Class
The WinForms ListBox class doesn't do it exactly like this because it was written before generics were introduced to the framework. But since they're here now, and you should always use them when possible, you can completely ignore how WinForms does things.

Is there a native LINQ way to return a typed collection in this example?

Is this the most straight forward way to return a typed collection?
Sorry for the repeated question. Now I am looking for a better way...
Here's the key line of code which returns a implicit type of IEnumerable that used to manually loop through to manually recreated a TYPED collection. Is there any native LINQ way to return a typed sorted collection without this recreating of the collection?
Dim Sorted As ErrorProviderMessageCollection = New ErrorProviderMessageCollection(From item In MyCollection Order By item.Control.TabIndex)
Public Class ErrorProviderMessageCollection
Inherits System.Collections.ObjectModel.Collection(Of ErrorProviderMessage)
Public Sub New()
End Sub
Public Sub New(ByVal source As IEnumerable(Of ErrorProviderMessage))
Dim orderedCollection = New ErrorProviderMessageCollection()
For Each Item As ErrorProviderMessage In source
Me.Add(Item)
Next
End Sub
End Class
Public Class ErrorProviderMessage
Public Sub New(ByVal message As String, ByVal control As Control)
_Message = message
_Control = control
End Sub
Public ReadOnly Property Message() As String
Public ReadOnly Property Control() As Control
End Class
The key point to remember about LINQ is that it's based on deferred execution.
If you do
Dim y = col.Where(Function(i) i.SomeProp = True)
You AREN'T actually creating a new collection. LINQ is creating an enumerator that executes on each item in col on demand.
So, the short answer is, no, LINQ yields items in an enumerable, it doesn't return new collections (with the exception of methods like ToList or ToArray or ToDictionary which force enumeration).
If you want a new typed collection, you need to force enumeration:
Dim col2 = New ErrorProviderMessageCollection(col.Where(Function(i) i.SomeProp = True))
No, there is no LINQ way of doing that, as the Collection<T> class is not one of the collection types that it uses.
You can turn the IEnumerable<T> into a List<T>, which implements IList<T>, and there is a constructor for Collection<T> that takes an IList<T>:
Dim Sorted As Collection<ErrorProviderMessage> = _
New Collection<ErrorProviderMessage>( _
(From item In MyCollection Order By item.Control.TabIndex).ToList() _
)