I need a simple LINQ query on VB.NET on the dictionary below, but I'm really new to the subject so I need your help.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim appEnums As New Dictionary(Of Integer, String)
appEnums.Add(1, "www.eva.com")
appEnums.Add(2, "www.eva2.com")
appEnums.Add(4, "www.evanetwork.com")
appEnums.Add(5, "www.eva3.com")
appEnums.Add(6, "www.eva4.com")
appEnums.Add(7, "www.eva5.com")
appEnums.Add(8, "www.eva6.com")
appEnums.Add(9, "www.eva1.com")
appEnums.Add(10, "www.eva7.com")
Dim startSite As Integer = 1
Dim mainSite As Integer = 4
Dim returnSite As Integer = 5
End Sub
What I need here is to retrieve a SINGLE website (dictionary value of string type) or NOTHING (if the query cannot find an affordable result) given those rules:
Any hint?
EDIT: thanks for the replies so far! I'm not sure they would work btw have to test them, at a first glance there is something odd.
I found a solution myself and it works perfectly (can't believe it) but I think there should be a more "elegant" way to it (in vb.net always). waiting for suggestions :)
Dim resultSite As String
Try
resultSite = appEnums.Where(Function(x) x.Key > startSite _
AndAlso x.Key <> mainSite AndAlso x.Key <> returnSite) _
.OrderBy(Function(x) x.Key).Select(Function(x) x.Value).First()
Catch
resultSite = Nothing
End Try
Here is a slightly more refined LINQ statement.
Dim resultSite As String =
appEnums.OrderBy(Function(kvp) kvp.Key)
.SkipWhile(Function(kvp) kvp.Key <= startSite)
.Where(Function(kvp) kvp.Key <> mainSite AndAlso kvp.Key <> returnSite)
.Select(Function(kvp) kvp.Value).FirstOrDefault()
It differs from your solution in two places:
OrderBy first, so that it can use SkipWhileFirstOrDefault so that it avoids the ugly try/catch block.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With