How to perform a count using LINQ? - sql-server

I am using SQL server and in my program I am currently using a count like this:
Function NumberOfApplications(inCandidateID As Integer) As Integer
Dim iCount As Integer = 0
Dim oApplication As DataModels.Application
For Each oApplication In Me.Applications
If oApplication.CandidateID = inCandidateID Then
iCount = iCount + 1
End If
Next
Return iCount
End Function
I have created my entities and bought in the correct Imports but I need to know how to perform a count using LINQ and VB. As you can see above I am using the Candidate ID to count. Any help would be appreciated. Thank you.

As #Pleun mentions, you can use the Count method, but the method itself has a predicate option, so you can use:
return Me.Applications.Count(app => app.CandidateID == inCandidateID);
In C#. I always have to think hard what that would look like in VB, this is what my brain tells me. The compiler migt disagree though ;):
Return Me.Applications.Count(Function(app) app.CandidateID = inCandidateID)

If you prefer the sql-like syntax, you could also do this:
Function NumberOfApplications(inCandidateID As Integer) As Integer
Return (From app As DataModels.Application In Me.Applications
Where app.CandidateID = inCandidateID).Count
End Function

Related

Inserting NULL integer using VB.Net and EF5

Working on an application that relies on an older version of entity, and I'm trying to insert a NULL into an int field. The field in SQL Server is (int, null).
Here's the definition of the object in EF:
<EdmScalarPropertyAttribute(EntityKeyProperty:=false, IsNullable:=true)>
<DataMemberAttribute()>
Public Property application_id() As Nullable(Of Global.System.Int32)
...and here is where I'm trying to set it:
applications.application_id = IIf(IsNumeric(txtAppID.Text), CInt(txtAppID.Text), Nothing)
The error thrown in response is:
An exception of type 'System.InvalidCastException' occurred in ... but was not handled in user code
Additional information: Specified cast is not valid.
I can confirm that this issue is being thrown due to the Nothing portion because previously it was applications.application_id = CInt(txtAppID.Text) and all was fine.
I've tried DBNull.Value instead of Nothing, though the error reads the same. Done a fair bit of research though most issues relate to ES6 or datetime fields, and as such I felt my issue was specific enough to warrant its own question.
Thanks.
The IIf function doesn't short circuit, and therefore always evaluates both the true and false parts, so it's not going to work in that situation. The If keyword does short circuit, but you will probably run into issues with the return type and nullable value types (e.g. Dim x As Integer? = If(False, 1, Nothing) results in x = 0 because the If is returning Integer and not Integer?).
So, I would recommend either using a regular If statement:
If IsNumeric(txtAppID.Text) Then
applications.application_id = CInt(txtAppID.Text)
Else
applications.application_id = Nothing
End If
or you could create a helper function:
Function NullableCInt(value As String) As Integer?
If IsNumeric(value) Then Return CInt(value)
Return Nothing
End Function
and use that:
applications.application_id = NullableCInt(txtAppID.Text)
You can get working If method with casting
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DirectCast(Nothing, Integer?))
For better readability you can introduce "default" value
Static DEFAULT_VALUE As Integer? = Nothing
Dim temp As Integer
applications.application_id = If(Integer.TryParse(value, temp), temp, DEFAULT_VALUE)
With Integer.TryParse you need "check/convert" string to integer only once.

How to pass Array[Long] ids into Aerospike Record UDF?

I store many sub records as Map in the same top record, now I need remove some sub records according to passing keys, I plan to use UDF to implement it. When I invoked from Java, the log shows the length is 0. Why? and how to correct this? Thanks!
In Java =>
val ids = Array(1,2,3)
Value.get(ids)
In Lua UDF =>
function remove_keys(rec, binName, rmkeys)
info("Value(%s) valType(%s)", tostring(rec), type(rec));
info("Value(%s) valType(%s)", tostring(binName), type(binName));
info("Value(%s) valType(%s)", tostring(rmkeys), type(rmkeys));
info("BinName(%s)", binName)
info("len(%s)", tostring(#rmkeys))
...
end
Try:
String binName = "binName";
List<Value> rmKeys = new ArrayList<Value>();
rmKeys.add(Value.get("key1"));
client.execute(policy, key, packageName, "remove_keys", Value.get(binName), Value.get(rmKeys));

Use the string stored in a Variant in an Array

I'm trying to use the values inside of a Variant.
An example of the code:
Dim Holder as Variant
Holder = "1,1,1,1,1"
Later I will be using this Variant inside of an Array().
The Declaration is like this:
.TextFileColumnDataTypes = Array(Holder)
There was an error right after this
Run-Time Error '5':
Invalid Procedure call or argument*
Is there a way to insert the Variant's values into Array(<Here?).
Holder's value is not constant, it will change depending on a function I created.
A way to accomplish this is as suggested in comments, using the split
If you are getting an error I am guessing that you are not using it correctly.
This is how the code should look.
dim i as long
dim var
Holder = "1,1,1,1,1"
var = Split(Holder,",")
for i = 0 to 4
.TextFileColumnDataTypes = var(i)
next i

VB 6.0 unable to create array

I am not able to create an array in VB 6.0 and I'm going crazy trying to figure it out. First of all VB is not my native language, I am a PHP programmer so arrays are not a new concept for me... Hopefully someone can help with this.
This is my function:
Function get_plant() As String
Dim arrPlant(1 To 10) As String
arrPlant(1) = "PL1"
arrPlant(2) = "PL2"
arrPlant(3) = "PL3"
arrPlant(4) = "PL4"
arrPlant(5) = "PL5"
arrPlant(6) = "PL6"
arrPlant(7) = "PL7"
arrPlant(8) = "PL8"
arrPlant(9) = "PL9"
arrPlant(10) = "PL0"
get_plant = arrPlant
End Function
Then I tried calling it with this (and about 10 other variations...):
Dim plant_code() As String
plant_code = get_plant()
MsgBox plant_code(1)
When I try and use the array I get this:
Question mark in the array index
What the heck am I missing here?
The return type of the function you have given is string not string() and you are trying to return string array. Try giving this
Function get_plant() As String()

visual basic array case statement

I'm new to visual basic and have been using vb.net to create a console/text based game. I want to make my game a little bit more "smart". The idea I've had to do this is to create an array of synonyms for yes and an array of synonyms for no, and similar arrays for over words. I intended on using a case statement with the array to decide weather the users input was a synonym for yes or for no. I have had no luck so far, and I was wondering if anybody here knew how it can be done or if I'm barking up the wrong tree. Maybe there is a different way for me to approach this?
My Select attempt:
Select Case userInput
Case yes(0) To yes(34)
Console.WriteLine("you said something like yes, you said {0}", userInput)
End Select
The start of my array: (there are 34 synonyms so far)
Dim yes(0 To 34) As String
yes(0) = "yes"
yes(1) = "ok"
yes(2) = "yep"
yes(3) = "yeah"
If anybody can help me it would be very much appreciated :) Thank you very much!
You do not have to use a Select Case for this purpose. A simple List(Of T).Contains can do the trick. Then you can go ahead to put it in a function so you can call it several times in your application.
Sample Code:
Public Enum Answer
Yes
No
Other
End Enum
Public Function GetAnswer(answer As String) As Answer
Static yesAnswers = New List(Of String)({"yes", "yeah", "yep", "aye"})
Static noAnswers = New List(Of String)({"no", "nope", "nay"})
If yesAnswers.Contains(answer.ToLower()) Then
Return Answer.Yes
ElseIf noAnswers.Contains(answer.ToLower()) Then
Return Answer.No
Else
Return Answer.Cancel
End If
End Function
I would create a translation dictionary
Dim translations As New Dictionary(Of String, String)
translations.Add("yes", "yes")
translations.Add("ok", "yes")
translations.Add("yep", "yes")
translations.Add("yeah", "yes")
translations.Add("no", "no")
translations.Add("nope", "no")
With these definitions you can get the standard version of an answer very easily
Dim userInput = "yeah"
Dim response As String = Nothing
translations.TryGetValue(userInput, response)
Select Case response
Case "yes"
Console.WriteLine("ok")
Case "no"
Console.WriteLine("cancel")
Case Else
Console.WriteLine("rubbish!")
End Select
Dictionaries have the fastest lookup times.

Resources