Find list value against certain key in Dictionary - vb.net

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...

Related

Create a dictionary from a list of lists VB.Net

I have a list of objects within another list. It looks like this:
Dim _elements as List(Of List(Of Element))
_elements(0) is a list of Element1, Element2, etc.
_elements(1) is a list of Element5, Element6, etc.
I need to create a dictionary of the elements so that the index of each list is the Key in the dictionary. The value of the dictionary should hold all elements of the Legend type that can be found in the list. Something like the following:
Dim legendElements As New Dictionary(Of Integer, List(Of Element))
' Initialize the list in the dictionary
For i As Integer = 0 To _elements.Count - 1
legendElements(i) = new List(Of Element)
Next
For i As Integer = 0 To _elements.Count - 1
For each element as Element in _elements(i)
If element.GetType() Is GetType(Legend) Then
legendElements.add(element)
End If
Next
Next
Is there a System.Linq function that can do the equivalent as the example above?
Call Enumerable.SelectMany method to get a flatten list of the target type which you filter by calling the Enumerable.Where method. Call the Enumerable.Select method to create from the result IEnumerable of anonymous objects to hold and pass the Legend objects along with their indices, and finally, call the Enumerable.ToDictionary method to create
Dictionary(Of Integer, Element) from the anonymous objects.
Dim legendElements As Dictionary(Of Integer, Element) = elements.
SelectMany(Function(x) x.Where(Function(y) y.GetType Is GetType(Legend))).
Select(Function(v, k) New With {Key .Key = k, .Value = v}).
ToDictionary(Function(a) a.Key, Function(a) a.Value)
Do the proper cast if you need a Dictionary(Of Integer, Legend).
Dim legendElements As Dictionary(Of Integer, Legend) = elements.
SelectMany(Function(x) x.Where(Function(y) y.GetType Is GetType(Legend))).
Select(Function(v, k) New With {Key .Key = k, .Value = v}).
ToDictionary(Function(a) a.Key, Function(a) DirectCast(a.Value, Legend))

Check for null value for value types in 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

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()

How do I use Linq ToDictionary to return a dictionary with multiple values in the dictionary items?

I want to group items from a linq query under a header, so that for each header I have a list of objects that match the header title. I assumed the solution would be to use ToDictionary to convert the objects, but this allows only one object per "group" (or dictionary key). I assumed I could create the dictionary of type (String, List Of()), but I can't figure out how to write it.
As an example I have written a simplified version below.
Public Class order
Public ID As Integer
Public Name As String
Public DateStamp As Date
End Class
Public Function GetOrdersSortedByDate() As Generic.Dictionary(Of String, Generic.List(Of User))
Dim orders As New List(Of order)(New order() _
{New order With _
{.ID = 1, .Name = "Marble", .DateStamp = New Date(2010, 1, 1)}, _
New order With _
{.ID = 2, .Name = "Marble", .DateStamp = New Date(2010, 5, 1)}, _
New order With _
{.ID = 3, .Name = "Glass", .DateStamp = New Date(2010, 1, 1)}, _
New order With _
{.ID = 4, .Name = "Granite", .DateStamp = New Date(2010, 1, 1)}})
' Create a Dictionary that contains Package values,
' using TrackingNumber as the key.
Dim dict As Dictionary(Of String, List(Of order)) = _
orders.ToDictionary(Of String, List(Of order))(Function(mykey) mykey.Name, AddressOf ConvertOrderToArray) ' Error on this line
Return dict
End Function
Public Function ConvertOrderToArray(ByVal myVal As order, ByVal myList As Generic.List(Of order)) As Generic.List(Of order)
If myList Is Nothing Then myList = New Generic.List(Of order)
myList.Add(myVal)
Return myList
End Function
The error is as follows
'Public Function ConvertOrderToArray(myVal As order, myList As System.Collections.Generic.List(Of order)) As System.Collections.Generic.List(Of order)'
does not have a signature compatible with delegate
'Delegate Function Func(Of order, System.Collections.Generic.List(Of order))(arg As order) As System.Collections.Generic.List(Of order)'.
What do I do to output a list for each dictionary item?
you could first group all your result by name and then call to dictionnary with the group key as key
i don't know how to code it in VB but what it would look like in C#
Dictionary<string,List<Order>> dict = orders
.GroupBy(x => x.Name)
.ToDictionary(gr => gr.Key,gr=>gr.ToList() );
Instead of ToDictionary, you want ToLookup. A lookup will store a list of values for each key, so the key is no longer required to be unique. The lookup returned from this method is immutable though.