How to convert a "custom class" to an arraylist?nc - asp.net

I have a class called student. Student class has public fields like first name, and last name. I am creating an instance of this class in my default page and assigning values to the fields. I have a function which takes two arraylists and return false if items in the arraylists do not match. In my default page, I have an arraylist which has items like first name and last name. I am passing this student object and the arraylist to compare and I get unable to cast Student to arraylist. Is there a way to work around this? Below is my code.
Dim valid as boolean = StudentsCompare(Student, arrlst)
Function StudentsCompare(ByVal arraylist1 as Arraylist, ByVal arrayList2 as ArrayList)
Dim Error As Boolean = True
For i As Integer = 0 To (arraylist1.Count - 1)
If Not arraylist1.Item(i).ToString = arrayList2.Item(i).ToString Then
Return Error = False
End If
Next
Return Error
End Function

You could do it this way; student.FirstName is an example you may need to change it with one of your class's real property.
Private valid As Boolean = StudentsCompare(List(Of Student), arrlst)
Private Function StudentsCompare(students As List(Of Student), list As ArrayList) As Boolean
Dim index As Integer = 0
For Each student As var In students
If student.FirstName = list(index).ToString() Then
Return False
End If
index += 1
Next
Return True
End Function
And If you have both parameter with the same object "Student" you could do it this way and check the multiple conditions:
Private list1 As List(Of Student)
Private list2 As List(Of Student)
Private valid As Boolean = StudentsCompare(list1, list2)
Private Function StudentsCompare(students1 As List(Of Student), students2 As List(Of Student)) As Boolean
For Each st1 As var In students1
For Each st2 As var In students2
If st1.FirstName = st2.FirstName AndAlso st1.LastName = st2.LastName AndAlso st1.Grade = st2.Grade Then
Return True
End If
Next
Next
Return False
End Function

Related

Use property value based on string

I have a search filter that goes through the list of customers that I have, and depending on whether the string contains the value or not, returns the list that satisfies the condition. Right now it checks the company property in the condition, but I'd like it to be able to check any property that's given in the method (customerDetail is the property name in this function). How can I pass the string property and make it work with this statement?
If(oListOfCustomers.Item(iIndex).Company.ToString.Trim.Contains(sStringContains) = True) Then
For clarification, I want something along the lines of:
If(oListOfCustomers.Item(iIndex).customerDetail.ToString.Trim.Contains(sStringContains) = True) Then
Here's the function:
Public Shared Function GetContains(ByVal sStringContains As String, ByVal customerDetail As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim oCustomer As Customer
'Property Names: Company, Contact, City, State, Country, Zip, Status
'Check for all properties. It works though.
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
For iIndex = 0 To oListOfCustomers.Count - 1
If (oListOfCustomers.Item(iIndex).Company.ToString.Trim.Contains(sStringContains) = True) Then
oCustomer = New Customer(oListOfCustomers.Item(iIndex).Company, oListOfCustomers.Item(iIndex).Contact, oListOfCustomers.Item(iIndex).Address1, oListOfCustomers.Item(iIndex).Address2, _
oListOfCustomers.Item(iIndex).City, oListOfCustomers.Item(iIndex).State, oListOfCustomers.Item(iIndex).Country, oListOfCustomers.Item(iIndex).Zip, _
oListOfCustomers.Item(iIndex).Zip4, oListOfCustomers.Item(iIndex).Email, oListOfCustomers.Item(iIndex).Phone, oListOfCustomers.Item(iIndex).Status, _
oListOfCustomers.Item(iIndex).MasterContactID)
oNewListOfCustomers.Add(oCustomer)
End If
Next
End If
Return oNewListOfCustomers
End Function
You could use reflection and PropertyInfo.GetValue. Try (untested):
Imports System.Reflection
Public Shared Function GetContains(ByVal sStringContains As String, ByVal customerDetail As String, ByVal oListOfCustomers As List(Of Customer))
Dim oCustomerData As New CustomerData
Dim oNewListOfCustomers As New List(Of Customer)
Dim iIndex As Integer
Dim oCustomer As Customer
Dim propertyInfo As PropertyInfo
'Property Names: Company, Contact, City, State, Country, Zip, Status
'Get PropertyInfo for customerDetail-property
propertyInfo = GetType(Customer).GetProperty(customerDetail)
'Check for all properties. It works though.
If IsNothing(oListOfCustomers) = False AndAlso oListOfCustomers.Count > 0 Then
For iIndex = 0 To oListOfCustomers.Count - 1
If (propertyInfo.GetValue(oListOfCustomers.Item(iIndex)).ToString.Trim.Contains(sStringContains) = True) Then
oCustomer = New Customer(oListOfCustomers.Item(iIndex).Company, oListOfCustomers.Item(iIndex).Contact, oListOfCustomers.Item(iIndex).Address1, oListOfCustomers.Item(iIndex).Address2,
oListOfCustomers.Item(iIndex).City, oListOfCustomers.Item(iIndex).State, oListOfCustomers.Item(iIndex).Country, oListOfCustomers.Item(iIndex).Zip,
oListOfCustomers.Item(iIndex).Zip4, oListOfCustomers.Item(iIndex).Email, oListOfCustomers.Item(iIndex).Phone, oListOfCustomers.Item(iIndex).Status,
oListOfCustomers.Item(iIndex).MasterContactID)
oNewListOfCustomers.Add(oCustomer)
End If
Next
End If
Return oNewListOfCustomers
End Function

Most efficient way to validate multiple textboxes against a tolerance value

I have a series of text boxes in a table to gather input as below:
The user will input a target and actual value for each measurement point they require. I would then like to validate the actual values against the target values based upon the tolerance inputted in the tolerance textbox. The tolerance will be the same for all measurement points inputted, however the user will not always input all 10 measurement points.
I have also created a very basic class containing a function that accepts the target, actual and tolerance values then returns a Boolean depending on whether the actual value is within tolerance. I realise I could use this with a ruck load of if statements to check each textbox for input then use the class to perform the validation, however this seems like a lot of code repetition and a bit crude. My question being is there a better way I can perform this validation?
EDIT Class content
Public Class TolerenceHelper
Public Function IsInTolerence(ByVal target As Integer, ByVal actual As Integer, ByVal tolerence As Integer) As Boolean
Dim upper As Integer = target + tolerence
Dim lower As Integer = target - tolerence
If actual < lower OrElse actual > upper Then
Return False
Else
Return True
End If
End Function
Calling the function as below:
Dim m1 As TolerenceHelper
Dim flag As Boolean = True
m1 = New TolerenceHelper
If m1.IsInTolerence(Integer.Parse(txtT1.Text), Integer.Parse(txtA1.Text), Integer.Parse(txtTolerance.Text)) = False Then
flag = False
End If
If flag = False Then
lblTest.Text = "Out of tolerance"
Else
lblTest.Text = "In tolerance"
End If
Your helper method seems to be ok, but you haven't shown the important part that you want to improve. The part where you load all textboxes and check whether they are valid or not.
Here is an approach that uses a custom class Measurement. You can use
Math.Abs(target.Value - actual.Value) <= tolerance
to determine if the value is valid according to the target and the tolerance.
Public Class Measurement
Public Property Tolerance As Int32
Public Property Target As Int32
Public Property Value As Int32
Public ReadOnly Property IsValid As Boolean
Get
Return Math.Abs(Target - Value) <= Tolerance
End Get
End Property
End Class
I would add all textboxes into the same container control like a Panel. Then you could use Enumerable.OfType to find the relevant textboxes. I use Enumerable.Zip to bring the values and the targets together. Use Int32.TryParse to validate the text.
Dim tolerance As Int32
If Not Int32.TryParse(txtTolerance.Text, tolerance) Then
lblTest.Text = "Enter a valid tolerance! Tolerance must be a positive integer(incl. zero)."
Return
End If
Dim value As Int32
Dim allTxtTarget = From txt In Me.PnlMeasurement.Controls.OfType(Of TextBox)()
Where txt.ID Like "txtT#*" AndAlso Int32.TryParse(txt.Text, value)
Let x = New With {.TextBox = txt, .Value = value, .Type = "Target", .Number = txt.ID.Substring(4)}
Order By x.Number
Select x
Dim allTxtActual = From txt In Me.PnlMeasurement.Controls.OfType(Of TextBox)()
Where txt.ID Like "txtA#*" AndAlso Int32.TryParse(txt.Text, value)
Let x = New With {.TextBox = txt, .Value = value, .Type = "Value", .Number = txt.ID.Substring(4)}
Order By x.Number
Select x
Dim allMeasurements = allTxtTarget.Zip(allTxtActual,
Function(target, actual) New Measurement With {
.Tolerance = tolerance,
.Target = target.Value,
.Value = actual.Value
}).ToList()
Output the results:
For i As Int32 = 0 To allMeasurements.Count - 1
Dim m = allMeasurements(i)
Console.WriteLine("Measurement {0}: Tolerance:{1} Target:{2} Value:{3} Valid:{4}",
i+1, tolerance, m.Target, m.Value, m.IsValid)
Next
If you actually need to check if all or at least one measurement is valid you can use:
Dim allValid = allMeasurements.All(Function(m) m.IsValid)
Dim anyValid = allMeasurements.Any(Function(m) m.IsValid)
or to find the highest valid measurement:
Dim validMeasurements = From m In allMeasurements
Where m.IsValid
Order By m.Value Descending
Dim highestMeasurement = validMeasurements.FirstOrDefault()

Implement IComparer(Of DateTime) on list(of X) property

I want to sort all items in the list of the property reviews of the class CompanyTotalReview by the property reviewdatetime in descending order.
Here's what I have:
Dim allReviews As RestService.CompanyTotalReview = rst.getReviews(type, objectId, _lang)
Dim dc As New ReviewComparer
allReviews.reviews.Sort(dc)
Public Class CompanyTotalReview
Public Property totalreviews() As Integer
Get
Return _totalreviews
End Get
Set(value As Integer)
_totalreviews = value
End Set
End Property
Private _totalreviews As Integer
Public Property averagereview() As String
Get
Return _averagereview
End Get
Set(value As String)
_averagereview = value
End Set
End Property
Private _averagereview As String
Public Property reviews() As List(Of Review)
Get
Return m_reviews
End Get
Set(value As List(Of Review))
m_reviews = value
End Set
End Property
Private m_reviews As List(Of Review)
End Class
Public Class Review
Public Property overallscore() As Integer
Get
Return _overallscore
End Get
Set(value As Integer)
_overallscore = value
End Set
End Property
Private _overallscore As Integer
Public Property reviewtext() As String
Get
Return _reviewtext
End Get
Set(value As String)
_reviewtext = value
End Set
End Property
Private _reviewtext As String
Public Property reviewdatetime() As DateTime
Get
Return _reviewdatetime
End Get
Set(value As DateTime)
_reviewdatetime = value
End Set
End Property
Private _reviewdatetime As DateTime
End Class
updated class based on comments
Public Class ReviewComparer
Implements IComparer(Of RestService.Review)
Public Function Compare(xr As RestService.Review, yr As RestService.Review) As Integer Implements System.Collections.Generic.IComparer(Of RestService.Review).Compare
Dim x As DateTime = xr.reviewdatetime
Dim y As DateTime = yr.reviewdatetime
If x = Nothing Then
If y = Nothing Then
Return 0
Else
Return -1
End If
Else
If y = Nothing Then
Return 1
Else
Dim retval As Integer = x.CompareTo(y)
If retval <> 0 Then
Return retval
Else
Return x.CompareTo(y)
End If
End If
End If
End Function
End Class
You are sorting Review objects, not datetime objects. Use a review comparer like this.
Public Class ReviewComparer
Implements IComparer(Of Review)
Public Function Compare(xr As Review, yr As Review) As Integer Implements System.Collections.Generic.IComparer(Of Review).Compare
Dim x As DateTime = xr.reviewdatetime
Dim y As DateTime = yr.reviewdatetime
If x = Nothing Then
If y = Nothing Then
Return 0
Else
Return -1
End If
Else
If y = Nothing Then
Return 1
Else
Dim retval As Integer = x.CompareTo(y)
If retval <> 0 Then
Return retval
Else
Return x.CompareTo(y)
End If
End If
End If
End Function
End Class

LINQ - Putting result in a dictionary(Of String, Integer), where the integer must be 0

I have a LINQ2Entity problem, I want to get the value, string, from a database, so I select FProducts.Serial_number, and to end the query, I do .ToDictionary.
The problem is, it tells me that it doesn't have sufficient parameters, to convert ToDictionary.
So I need something like select FProducts.Serial_number, Nothing). ToDictionary.
Also FProducts.Serial_number, 0).ToDictionary doesn't work.
Any recommendations?
Sub GetStatistics(ByVal ProductNumbers As List(Of String), ByRef Passed As Integer, ByRef FailedProducts As List(Of String))
Passed = 0
FailedProducts = Nothing
Dim tpDictionary As Dictionary(Of String, Integer)
For Each productNumber As String In ProductNumbers
Using context As New SelmaEntities
Dim Table = (From GoodProducts In context.TestResults
Where (GoodProducts.Art_no = productNumber)
Select GoodProducts.Art_no, GoodProducts.Failed)
tpDictionary = (From FProducts In context.TestResults
Where (FProducts.Art_no = productNumber And FProducts.Failed <> 0)
Order By FProducts.Serial_number
Select FProducts.Serial_number, ).ToDictionary
End Using
Next
End Sub
ToDictionary requires lambda expressions as parameters: one to select the dictionary key, one to select the value. So try:
tpDictionary = (From FProducts In context.TestResults
Where (FProducts.Art_no = productNumber And FProducts.Failed <> 0))
.ToDictionary(Function(p) FProducts.Serial_number, Function(p) 0)
var products = from p in FProducts select new { value=serial_number,key=productid};
Dictionary<string, int> dictionary = new Dictionary<string, int>();
foreach(var item in products){
dictionary.Add(item.value, item.key);
}

get the value from 2-d arraylist in session

I have an 2-d arraylist with 2 fixed columns and dynamic rows. The arraylist will be assigned to the session variable at the end of the code below. My question is how can loop thorugh the arraylist from the session to get its value?
If .SQLDS.Tables(.sSQLDSTbl).Rows.Count > 0 Then
Dim NoOfAdjType(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1)
For iRow As Integer = 0 To .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1
If Not .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt") Is System.DBNull.Value Then
NoOfAdjType(0, iRow) = .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("productType")
NoOfAdjType(1, iRow) = Format(.SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt"), "#,##0.00")
End If
Next
Session("iNoOfAdjAmtType") = NoOfAdjType
End If
I have tried this but it's giving me error 'Too many arguments to 'Public Overridable Default Property Item(index As Integer) As Object'
Dim NoOfAdjType As ArrayList = CType(Session("iNoOfAdjAmtType"), ArrayList)
For i As Integer = 0 To NoOfAdjType.Count
Dim a As String = NoOfAdjType(0, i)
Dim b As String = NoOfAdjType(1, i)
Next
The type you are dealing with is Object(,). So when reading from the session you can cast it back to this type.
Here's an article on MSDN which illustrates how to read values from session:
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
' do something with the list
And if you wanted to perform the check safely ensuring that there is an item with the given id in the session:
If Session.Item("iNoOfAdjAmtType") IsNot Nothing Then
' We have a value in the session with the given id
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
End If
I am not certain what is the data-type of array, but this how you manipulate the multi-dimension arrays in VB.NET assuming data-type as object
' declaring variable of multi-dim array
Dim NoOfAdjType As Object(,)
' create array object of needed dimension (you may use redim keyword)
NoOfAdjType = new Object(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1) {}
...
' push it in session
Session("iNoOfAdjAmtType") = NoOfAdjType
...
' get back from session
NoOfAdjType = DirectCast(Session("iNoOfAdjAmtType"), Object(,))
...
For i As Integer = 0 To NoOfAdjType.GetLength(0)
For j As Integer = 0 To NoOfAdjType.GetLength(1)
Dim a As Object = NoOfAdjType(i, j);
...
Next
Next
See this MSDN article for array in VB.NET: http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
Try this,
Dim a As String = NoOfAdjType(0)(0,0)
Or use
For Each arr As Object(,) In NoOfAdjType
Next

Resources