Using Linq order by an object's property Vb.Net - vb.net

I have a datatable of pointshape Objects in a map and I want to order this list by Object.baseshape.label.y which is a double value. How can I do this using Linq?
I Have implemented this code so far
Dim query As IEnumerable(Of DataRow) = From result In dataArray.AsEnumerable() Order By result.Field(Of Object)("MapShapes") Descending
but I want something like this
Dim query As IEnumerable(Of DataRow) = From result In dataArray.AsEnumerable() Order By result.Field(Of Object)("MapShapes")..baseshape.label.y Descending

You can use the specific object type in the Field(Of ...) like this...
Dim query = From result In dataArray.AsEnumerable() Order By result.Field(Of MapSuite.BaseMapShape)("MapShapes").label.y Descending

Related

How to return a List(Of String) from a LINQ statement with a Group By in VB.net?

I've seen several questions on how to do this in C# but I'm having trouble translating those to VB. Here's the basics of my issue:
Table of data NOT normalized and accessed via Entity Framework
Get all unique string values in a certain field
Convert those values to a List(Of String)
This works but I'm guessing there's a better way to do it without iterating through the list:
Public Function GetGroups() As IEnumerable(Of String)
Dim GroupList As New List(Of String)
Dim CodeList = (From c In Context.Codes
Group c.Group By c.Group Into g = Group)
For Each c In CodeList
GroupList.Add(c.Group)
Next
Return GroupList
End Function
What I seem to be struggling with the most is using Group By in LINQ. I'm guessing this could probably be done in 1 or 2 lines by having LINQ return just the list of strings or by converting the list of anonymous objects to a list of strings.
Well, if you don't need anything in the group, you can just use .Distinct():
Return (
From c In Context.Codes
Order By c.Group
Select c.Group
).Distinct().ToList()
Edit: Added Order By

Converting LINQ to dictionary in vb.net

I'm trying to convert LINQ to dictionary in vb.net, but can't seem to understand why I get all these exceptions thrown at me.
All I'm trying to do, is to sort by descending value with help from LINQ.
Here's my code:
'Declaring my primary dictionary
Dim nameValDict As New Dictionary(Of Object, Object)
... nameValDict is now getting filled up with data
'Declaring temporary sorted dictionary with LINQ
Dim sortedDict = (From entry In nameValDict Order By entry.Value Descending Select entry)
'Replace with sorted results from LINQ
nameValDict = sortedDict.ToDictionary(Function(x) x.Key, Function(x) x.Value)
Exception: System.ArgumentException (Object should be of type Double) - On last line.
I'll appreciate ANY help.
Its properly your Order By in this statement:
From entry In nameValDict Order By entry.Value Descending Select entry
Becuase entry.Value is of type Object, and you can't sort desending on Object. The program doesnt know how to compare Objects against eachother.

Error when using linq on datatable

I am trying to run the following code converting my datatable to be usable in linq all seems fines and compiles but when I Execute the statement I get the following statement i get the error below new entires just has location and ordernumber in the return values I have to do it this way as I am supporting a legacy access 97 system thanks.
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int32)("location") Distinct
retVal = Convert.ToInt32(total)
This is my whole code but im still getting an invalid type cast error their is data exsits for this order by teh way
Dim retVal As Int32
Dim newEntries As New DataTable
Dim script As String = scriptBuilder.GetDistinctOrdersForLocations(OrderNumber)
newEntries = connection.SqlSelectToDataTable(script)
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int32)("location") Distinct
retVal = total.Count()
If you want the count of the collection just do this:
retVal = total.Count()
this will return the count from the distinct query that you have written.
Just to clarify, #David B identified the data type of location was int16 not int32, so changing this in the linq query resolved the issue.
Your LINQ query is returning a collection. You should use something like First or FirstOrDefault.
I'm a little rusty on VB LINQ, but try :
retVal = Convert.ToInt32(total.First())
Note: This will throw an error if there are no items in the collection.
It's important to understand when you write a LINQ query and assign it to a variable, that variable essentially contains a query object, and not the results of running the query. In order to get the value that results from the query, you need to call some method on the query object such as:
total.Single() ' Assumes you expect the query to return exactly one result.
I changed the code to int16 worked here is the code for any one else stuck thanks #Ric
Dim retVal As Int32
Dim newEntries As New DataTable
Dim script As String = scriptBuilder.GetDistinctOrdersForLocations(OrderNumber)
newEntries = connection.SqlSelectToDataTable(script)
Dim total = From row In newEntries.AsEnumerable()
Select row.Field(Of Int16)("location") Distinct
retVal = total.Count()

Sorting a List by the second column in VB

I am using a loop that builds a list of filenames and their creation dates:
Dim datelist As New List(Of KeyValuePair(Of String, Date))
Dim values As New KeyValuePair(Of String, Date)(filename, initialdate)
If Not datelist.Contains(values) Then
datelist.Add(values)
End If
After the list is populated, I need to sort it by date before performing some other functions.
I've been looking at an orderby or sort method, but I can't figure out how to implement them correctly. Can someone give me a hand?
This sorts the original list without creating a new list (like the Linq methods) using List.Sort:
datelist.Sort(Function(kv1, kv2) kv1.Value.CompareTo(kv2.Value))
Dim sorted = (From item In datelist Order By item.Value Select item).ToList
should do the trick
What's wrong with just using some simple LINQ?
Dim orderedList As List(Of KeyValuePair(Of String, Date)) = datelist.OrderBy(Function(o) o.Value).ToList

Sorting numbers in descending order

I have 20 textboxes. each contains a particular number . I want the textbox1 to textboxN to have the numbers in the descending order. If any of the textbox has a zero value then I want to leave that textbox as it is. A sample code in vb.net needed.
'for sorting the elements in descending order
dim array(4) as integer
array(4)={4,6,2,9,1}
'first sort the array and then reverse it as
array.sort(4)
array.reverse(4)
sortlistbox.item.add(array(4))
Dim txt As New List(Of TextBox)
Dim q = From i In txt
Where CInt(i.Attributes("value")) > 0
Order By CInt(i.Attributes("value")) Descending
Select i
Whana try some simple linq query over your collection?
This one is a bit old, but I ran into the same problem.
Using MSDN I found this: Enumerable.OrderBy Method (IEnumerable, Func)
If you just add .Reverse to that query, it's descending:
Dim query As IEnumerable(Of Pet) = pets.OrderBy(Function(pet) pet.Age).Reverse
#Thom Morgan
This one is a bit old, but I ran into the same problem.
Using MSDN I found this: Enumerable.OrderBy Method (IEnumerable, Func)
If you just add .Reverse to that query, it's descending:
Dim query As IEnumerable(Of Pet) = pets.OrderBy(Function(pet) pet.Age).Reverse
This worked like a charm! Thank you!