VB.NET and LINQ query on a dictionary
15,499
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:
- It uses
OrderBy
first, so that it can useSkipWhile
- It uses
FirstOrDefault
so that it avoids the uglytry/catch
block.
Author by
Admin
Updated on June 08, 2022Comments
-
Admin almost 2 years
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:
- The dictionary key (integer) must be greater than startSite and not equal to mainSite or returnSite (both must be exluded from the result)
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
-
dlras2 about 12 yearsI wouldn't use
Skip
, since it requires that the dictionary be in strictly ascending order. -
Admin about 12 yearsyep. And i need just one yes and also need to return nothing if I'm on the last key already (startSite).
-
Admin about 12 yearsI 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 :) I cannot post here for other 7 hours since I have low rep.. add in the main topic right now!