LINQ Count problems while trying to access to subList from a List of Objects (VB.NET) - vb.net

I'm having a pretty tough time figuring it out why it doesn't work properly but I'm asking for it.
Dim goodCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status <> TargetRange.OutOfRange
Select item).Count()
Dim badCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item).Count()
EquipmentTagList is a List(Of MachineTag) (custom object) so I want to get how many MachineTag from the EquipmentTagList matches the criteria. I'm still confused about why the first one works but not the other one. I know by debugging that the first one returns at least one result while the other returns nothing... I've searched a lot to get help for this error but unfortunately found nothing...
Thanks for helping me out.
EDIT:
The error I get is :
System.InvalidOperationException with Object reference not set to an instance of an object

Assuming for the moment that item.Status is an Integer data type (inferred from your use of TargetRange.OutOfRange as though it's an Enum), the syntax in your second snippet would be expected to fault.
The .Contains() method is reserved for use with IEnumerable objects, not Integer values.
If you modify your code slightly, to this:
Dim badCount = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item)
...and then set a breakpoint at some point after this call, you'll note that badCount is Nothing. Since Nothing can't have a .Count, the call fails.
Your first snippet is correct—as you've already pointed out.
EDIT
Something's not right here. Your code shouldn't even compile.
Here's what I'm getting:
So item.Status certainly can't be an Integer.

Maybe this will make it a bit easier. You can group by Status after filtering by Importance:
Dim items = From i In equipmentTagList Where i.Importance = "Critique"
Dim counts = items.ToLookup(Function(i) i.Status <> TargetRange.OutOfRange)
Dim goodCount = counts(True).Count()
Dim badCount = counts(False).Count()

Related

GetType does not exist a Reflection puzzle in VB

This is a real basic schoolboy level error but I've not figured it out yet despite having used a fair amount of reflection in my generic updater class.
The puzzle is as follows: I want to get the type of a value that I've extracted in the code sample. Using that type I wish to compare it with another extracted value. To compare it correctly with Option Strict On I must directCast the extracted value to the type that the PropertyInfo says it is.
The code below simply illustrates my using it in Directcast or Ctype versions.
For Each p As PropertyInfo In _validProperties
Dim NewValue = p.GetValue(UpdateItem)
Dim x = CType(NewValue, p.PropertyType) 'Error p.PropertyType does not exist --How?
'Elided
Next
'Alternative approach
For Each p As PropertyInfo In _validProperties
Dim NewValue = p.GetValue(UpdateItem)
Dim x = DirectCast(NewValue, p.PropertyType) 'Error p.PropertyType does not exist --How?
'Elided
Next
I've tried explicitly putting the newly discovered type in it's own variable and it does exist.
This is an odd little trap I've had a few times and usually solved but this one is not budging. Therefore I'm fundementally misunderstanding how I need to use both the instance x.Gettype (OR GetType(Class) syntaxes).
Whatever I do, p.PropertyType does not exist.
Can anyone clear up my foggy mind on this please?
Edit: For now, Option Strict is off merely to allow this to work.
For Each p In _validProperties
Dim NewValue = p.GetValue(UpdateItem), OriginalValue = p.GetValue(originalItem)
If (p.PropertyType.Name.Contains("Nullable") AndAlso Not Nullable.Equals(NewValue, OriginalValue)) _
OrElse NewValue <> OriginalValue Then p.SetValue(originalItem, NewValue)
Next
All my tests pass so I'll live with it for now. I simply don't want the update to fire if there is no difference between the values on the properties in question.

For each is printing same Item

The variable ListofBloodType is returning the correct values not sure why in the loop I am getting the first value 4 times ( the count 4 is correct also but printing the first value 4 times is not)
Dim tempTreatmentForBloodType As List(Of BloodType) = New List(Of BloodType)()
Dim ListofBloodType = getPatientBloodType(i.PatientID)
For Each i As PatientBloodType In ListofBloodType
tempTreatmentForBloodType.Add(([Enum].Parse(GetType(BloodType), getReference().Description)))
Next
The problem was exactly what GSerg pointed at, I was not using the loop variable. I created new getReference method with parameter to get the data for a particular patient. Here is the code that worked for me! I hope it helps new VB programmers like me!
Dim tempTreatmentForBloodType As List(Of BloodType) = New List(Of BloodType)()
Dim ListofBloodType = getPatientBloodType(i.PatientID)
For Each i As PatientBloodType In ListofBloodType
tempTreatmentForBloodType.Add(([Enum].Parse(GetType(BloodType),
getReference(i.PatientID).Description)))
Next
Many Thanks to the above helpful comments!

How to get an object out of a collection in VBa

I used to have the following working code
Set result = DecodeJson(MyRequest.responseText)
Dim keys() As String
keys = GetKeys(result.issues)
Now, my approach has changed and instead of having result being the object, I receive a Collection based upon Array of class objects as class member in VBA
Dim resultsFromQueries As Collection
Set resultsFromQueries = GetAllJSonObjects(searchString) ' this calls DecodeJson(MyRequest.responseText) as per the code snippet above
Dim i As Integer
For i = 0 To resultsFromQueries.Count
Dim keys() As String
Dim item As Object
Set item = resultsFromQueries.item(i + 1) ' I guess it's not 0 based?
keys = GetKeys(item.result.issues) 'KABOOM
The issue I have now is I keep getting the following exception
Run time error '424':
Object required
Checking in the watch window, item shows as type Variant/String and has the value of "[object Object]"
Do I need to cast it?
I had that problem just a few weeks ago, the problem was the following:
The collection was collected with the follwing code:Collection.Add(OBJECT)
This however leads to the addition of the value of the Object into the Collection and can be solved as simple as leaving the parathesis.Collection.add OBJECT
So my advice is to go into the GetAllJSonObjects(searchString) function and
search for the addition process and make sure that it is without parethesis.
Like this the Collection will contain Objects and not variants and your code with item(i+1) should work properly.
Good luck!

Linq Filter - After Filter Expecting Result Should be Nothing

Please check below code, as my question related to following example.
Dim objPOSMaxDiscountTemplateDetailList As POSMaxDiscountTemplateDetailList
objPOSMaxDiscountTemplateDetailList = _
POSMaxDiscountTemplateDetailList.GetPOSMaxDiscountTemplateDetailList(UserDiscountPolicyTemplateCode)
'Filtering Above List
Dim Data = (From p In objPOSMaxDiscountTemplateDetailList _
Where p.ItemTypeCode = ItemTypeCode)
If Data IsNot Nothing Then
'' Do Something
End If
In above example objPOSMaxDiscountTemplateDetailList object am getting 14 records. After that am filtering those record with ItemTypeCode condition and there is no matched record with ItemTypeCode. So I am expecting Data object will be nothing. But while debugging i found Data object is not nothing and data.count am getting 0.
I don't understand this behavior, as same type of coding i made some other class which running perfectly as per my expectation.
Thanks.
It won't be Nothing. It will be an empty collection. LINQ to Objects query almost never returns Nothing.
Try
If Not Data.Any() Then
'' Do Something
End If

Query results don't match NumFound when using SolrNet with VB.NET

I have implemented SolrNet in a VB.NET web site and it's working perfectly with one exception. My results object may tell me that 10 matching "documents" have been found but the collection only contains 9.
My collection always contains 1 less than the NumFound property states. I have run the queries directly through my Solr instance and I know that the NumFound property is reflecting the correct value. Having reviewed the returned documents I can see that the first document in each result set is missing from my collection i.e. the one at position 0.
This seems like a problem connected to a zero indexed collection.
I can't see that I'm doing anything wrong and suspect that this is a bug. Has anyone else experienced this or can you suggest where I may have gone wrong?
Source code is as follows
Private Prods As New SolrQueryResults(Of BLL.solrProduct)
Dim solr As ISolrOperations(Of BLL.solrProduct) = ServiceLocator.Current.GetInstance(Of ISolrOperations(Of BLL.solrProduct))()
Dim SolrQueryOptions As New SolrNet.Commands.Parameters.QueryOptions() With {.Stats = New StatsParameters(), .Start = PagingCurrent, .Rows = PagingSize, .Facet = New FacetParameters() With { _
.MinCount = 1, .Queries = New SolrNet.ISolrFacetQuery() {New SolrFacetFieldQuery("brand")}}}
SolrQueryOptions.Stats.AddField("selling_price")
SolrQueryOptions.FilterQueries.Add(New SolrQueryByField("brand", "puma"))
Prods = solr.Query("shirt", SolrQueryOptions)
PagingTotal = Prods.NumFound 'This returns 10
lv_prods.DataSource = Prods
lv_prods.DataBind() 'This renders 9 items
Solr pagination is zero-based, i.e. the first item corresponds to Start=0