Check for null value for value types in VB.NET - vb.net

I have a KeyValuePair(Of TKey,TValue) and I want to check if it is null or not:
Dim dictionary = new Dictionary(Of Tkey,TValue)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = *someValue*)
If keyValuePair isNot Nothing Then 'not valid because keyValuePair is a value type
....
End If
If keyValuePair <> Nothing Then 'not valid because operator <> does not defined for KeyValuePair(of TKey,TValue)
...
End If
How can I check if keyValuePair is null or not?

KeyValuePair(Of TKey, TValue) is a struct(Structure), it has default value which you can compare to.
Dim dictionary As New Dictionary(Of Integer, string)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = 2)
Dim defaultValue AS KeyValuePair(Of Integer, string) = Nothing
If keyValuePair.Equals(defaultValue) Then
' Not found
Else
' Found
End If
Nothing represents default value of the corresponding type.
But because you are searching Dictionary for a key, you can use TryGetValue instead
Dim dictionary As New Dictionary(Of Integer, string)
Dim value As String
If dictionary.TryGetValue(2, value) Then
' Found
Else
' Not found
End If

Related

Convert a List to a Dictionary with a unique numbered key

How can this code be accomplished using ToDictionary() instead of a For Each
Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)
Dim stringList As List(Of String) = {"alpha", "beta", "gamma", "delta"}
For Each stringItem As String In stringList
stringDict.Add($"Entry{stringDict.Count+1}",stringItem)
Next
This is what I am trying to do:
Dim stringDict As Dictionary(Of String, String) = stringList.ToDictionary(Function(a) $"Entry{?}", Function(b) b)
I was hoping there might be a variable with the current row or index, or an incrementor
You can use the overload of Select that gives you the index:
Dim stringDict As Dictionary(Of String, String) = stringList.
Select(Function(s, index) (Key:=$"Entry{index + 1}", Value:=s)).
ToDictionary(Function(kv) kv.Key, Function(kv) kv.Value)
However, i find your loop more readable. You should also set Option Strict to On, following should give you a compiler error:
Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)
You can use Enumerable.Range (documentation) to create a range of numbers from 1 to the Count of your List and then Enumerable.ToDictionary (documentation) to convert that range to a Dictionary.
Example:
Dim stringList As New List(Of String) From {"alpha", "beta", "gamma", "delta"}
Dim stringDict = Enumerable.Range(1, stringList.Count).ToDictionary(Function(i) $"Entry{i}", Function(i) stringList.Item(i - 1))
Fiddle: https://dotnetfiddle.net/4xHp9g

Find list value against certain key in Dictionary

I have a dictionary with int and List(of Type) , How can i check if certain key contains certain list value in dictionary.
I have a value and a key and i want to check if value exists that key.
So in following dictionary, Key 1 and value Result_3 should return true
Dim d as new dictionary(of int32, list(of Type))
d.Add(1,
New List(Of Type)(New Type() _
{GetType(Result_1),
GetType(Result_2),
GetType(Result_3),
GetType(Result_4)}))
d.Add(2,
New List(Of Type)(New Type() _
{GetType(Result_5),
GetType(Result_6)}))
d.Add(3,
New List(Of Type)(New Type() _
{GetType(Result_7)}))
I have tried this so far but no luck;
if d.Where(function(o) o.Value.Contains(GetType(Result_2)) ).Select(Function(n) n.Key = 1) then
End If
Try with this function
Function Check(key as int, value as Type) As Boolean
Return d(key).Contains(value)
End Function
And your example would be
If Check(1,GetType(Result_3)) Then...

VB dictionary contains value return key

I have a problem...
I am trying to put into a list of String dictionary keys values if condition of containsvalue is true:
But, this is not correct :(
here is a code:
Private listID As New List(Of String) ' declaration of list
Private dictionaryID As New Dictionary(Of String, Integer) ' declaration of dictionary
'put a keys and values to dictionary
dictionaryID.Add("first", 1)
dictionaryID.Add("second", 2)
dictionaryID.Add("first1", 1)
If dictionaryID.ContainsValue(1) Then ' if value of dictinary is 1
Dim pair As KeyValuePair(Of String, Integer)
listID.Clear()
For Each pair In dictionaryID
listID.Add(pair.Key)
Next
End If
And now, list must have two elements... -> "first" and "first1"
Can you help me?
Thank you very much!
You are looping through the whole dictionary and add all the elements to the list. You should put an if statement in the For Each or use a LINQ query like this:
If listID IsNot Nothing Then
listID.Clear()
End If
listID = (From kp As KeyValuePair(Of String, Integer) In dictionaryID
Where kp.Value = 1
Select kp.Key).ToList()
Using an if statement:
listID.Clear()
For Each pair As KeyValuePair(Of String, Integer) In dictionaryID
If pair.Value = 1 Then
listID.Add(pair.Key)
End If
Next
My VB.Net is a little rusty, but it looks like you were adding all of them, no matter if their value was 1 or not.
Private listID As New List(Of String) ' declaration of list
Private dictionaryID As New Dictionary(Of String, Integer) ' declaration of dictionary
'put a keys and values to dictionary
dictionaryID.Add("first", 1)
dictionaryID.Add("second", 2)
dictionaryID.Add("first1", 1)
If dictionaryID.ContainsValue(1) Then ' if value of dictinary is 1
Dim pair As KeyValuePair(Of String, Integer)
listID.Clear()
For Each pair In dictionaryID
If pair.Value = 1 Then
listID.Add(pair.Key)
End If
Next
End If

Filter a Dictionary to return a list

I know I can do this with a for loop cause that's how i'm doing it now. I was hoping for a more efficient way to accomplish the task.
I have a dictionary(Of Integer, Boolean)
or Of String, Boolean.
i want to get a list(of integer) or Of String from the dictionary where all the values are true(or false depending on what i need at the time)
and to generalize it or "black box" it, it could be any dictionary(of whatever, whatever)
and return a list(of whatever) where the value = whatever i'm looking for at the time.
string, string where value = "Closed"
in short: i want all list of all the keys who's value = some criteria
my current code:
Public Function FindInDict(Of tx, ty)(thedict As Dictionary(Of tx, ty), criteria As ty) As List(Of tx)
Dim tmpList As New List(Of tx)
For xloop As Integer = 0 To thedict.Count - 1
If CType(thedict(thedict.Keys(xloop)), ty).Equals(criteria) Then
tmpList.Add(thedict.Keys(xloop))
End If
Next
Return tmpList
End Function
You can do this easily with Linq:
Public Function FindInDict(Of tx, ty)(thedict As Dictionary(Of tx, ty), criteria As ty) As List(Of tx)
Return (From kvp In thedict
Where kvp.Value.Equals(criteria)
Select kvp.key).ToList()
End Function
Use LINQ, like so:
Dim tStorage As Dictionary(Of String, String) = New Dictionary(Of String, String)
Dim tKeys As List(Of String) = New List(Of String)
Dim tCriteria As List(Of String) = New List(Of String)
tStorage.Add("One", "Uno")
tStorage.Add("Two", "Dos")
tStorage.Add("Three", "Tres")
tStorage.Add("Four", "Quatro")
tCriteria.Add("Dos")
tCriteria.Add("Quatro")
tKeys = (From k In tStorage.Keys Where tCriteria.Contains(tStorage(k)) Select k).ToList
For Each tKey As String In tKeys
Console.WriteLine(tKey)
Next
Console.ReadKey()

For each loop not skipping items

I have a for each loop in vb.net for this particular example there are 2 items in list but after the first item the loop exits are there errors in the code
Public Function findUserID(ByVal list As List(Of KeyValuePair(Of String, String)), ByVal value As String)
Dim id As String = String.Empty
For Each kvp In list
If (kvp.Value = value) Then
id = kvp.Key
End If
Next
Return id
End Function
Try to use this:
dim kvp as KeyValuePair
kvp = list.Find(p=>p.Value = value))
if kvp = null then return "" else return kvp.Key
One user told me to modify it in this way:
dim kvp = list.Find(Function(e) e.Value = value)
If kvp Is Nothing Then Return "" Else Return kvp.Key
Sorry if this code has some error, but I cannot try and I usually write in C#.
So my code (in C#) would be:
KeyValuePair kvp = list.Find(p=>p.Value == value));
return kvp == null ? "" : kvp.Key;
Why you have the id variable and don't return the Key directly if you found a valid?
So the collection will loop through all KeyValuePairs and not stop on any results.
Public Function FindUserID(ByVal list As List(Of KeyValuePair(Of String, String)), ByVal value As String)
For Each kvp In list
If (kvp.Value = value) Then
Return kvp.Key
End If
Next
End Function
But thats not the error, did you debug the method and verified that there are more than one KeyValuePairs in the list?