I am learning about collections, I have a Person class
Imports System
Imports System.Collections.Generic
Imports System.Text
Public Class Person
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal first_name As String, ByVal mid_name As String, ByVal last_name As String, ByVal age As Short, ByVal sex As Char)
Me.p_id = id
Me.first_name = first_name
Me.mid_name = mid_name
Me.last_name = last_name
Me.p_age = age
Me.p_sex = sex
End Sub
Private p_id As Integer = -1
Private first_name As String = String.Empty
Private mid_name As String = String.Empty
Private last_name As String = String.Empty
Private p_age As Short = 0
Private p_sex As Nullable(Of Char) = Nothing
Public Property ID() As Integer
Get
Return p_id
End Get
Set(ByVal value As Integer)
p_id = value
End Set
End Property
Public Property FirstName() As String
Get
Return first_name
End Get
Set(ByVal value As String)
first_name = value
End Set
End Property
Public Property MiddleName() As String
Get
Return mid_name
End Get
Set(ByVal value As String)
mid_name = value
End Set
End Property
Public Property LastName() As String
Get
Return last_name
End Get
Set(ByVal value As String)
last_name = value
End Set
End Property
Public Property Age() As Short
Get
Return p_age
End Get
Set(ByVal value As Short)
p_age = value
End Set
End Property
Public Property Sex() As Nullable(Of Char)
Get
Return p_sex
End Get
Set(ByVal value As Nullable(Of Char))
p_sex = value
End Set
End Property
End Class
and an Employee Class where I define a Person property
Imports System
Imports System.Collections.Generic
Imports System.Text
Public Class Employee
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal companyName As String, ByVal office As String, colPerson As Person)
'Me._employeeid = id
'Me._companyName = companyName
'Me._office = office
End Sub
Private _employeeid As Integer = -1
Private _companyName As String = String.Empty
Private _office As String = String.Empty
Public Property Empoyee_ID() As Integer
Get
Return _employeeid
End Get
Set(ByVal value As Integer)
_employeeid = value
End Set
End Property
Public Property CompanyName() As String
Get
Return _companyName
End Get
Set(ByVal value As String)
_companyName = value
End Set
End Property
Public Property Office() As String
Get
Return _office
End Get
Set(ByVal value As String)
_office = value
End Set
End Property
Property colPerson As List(Of Person)
End Class
How can i populate the persons class as well
Sub Main()
Dim pList As List(Of Person) = New List(Of Person)()
Dim thePerson As New List(Of Person) From
{
New Person With {.Age = 29, .FirstName = "John", .LastName = "Shields", .MiddleName = "", .Sex = "M", .ID = 1},
New Person With {.Age = 34, .FirstName = "Mary", .LastName = "Matthew", .MiddleName = "L", .Sex = "F", .ID = 2},
New Person With {.Age = 55, .FirstName = "Amber", .LastName = "Carl", .MiddleName = "P", .Sex = "M", .ID = 3},
New Person With {.Age = 12, .FirstName = "Kathy", .LastName = "Berry", .MiddleName = "O", .Sex = "F", .ID = 4}
}
'pList.Add(New Person(1, "John", "", "Shields", 29, "M"c))
'pList.Add(New Person(2, "Mary", "Matthew", "Jacobs", 35, "F"c))
'pList.Add(New Person(3, "Amber", "Carl", "Agar", 25, "M"c))
'pList.Add(New Person(4, "Kathy", "", "Berry", 21, "F"c))
'pList.Add(New Person(5, "Lena", "Ashco", "Bilton", 33, "F"c))
'pList.Add(New Person(6, "Susanne", "", "Buck", 45, "F"c))
'pList.Add(New Person(7, "Jim", "", "Brown", 38, "M"c))
'pList.Add(New Person(8, "Jane", "G", "Hooks", 32, "F"c))
'pList.Add(New Person(9, "Robert", "", "", 31, "M"c))
'pList.Add(New Person(10, "Cindy", "Preston", "Fox", 25, "F"c))
'pList.Add(New Person(11, "Gina", "", "Austin", 27, "F"c))
'pList.Add(New Person(12, "Joel", "David", "Benson", 33, "M"c))
'pList.Add(New Person(13, "George", "R", "Douglas", 55, "M"c))
'pList.Add(New Person(14, "Richard", "", "Banks", 22, "M"c))
'pList.Add(New Person(15, "Mary", "C", "Shaw", 39, "F"c))
'
'loop through the list
' PrintOnConsole(pList, "1. --- Looping through all items in the List<T> ---")
'
'Filtering List(T) using a single condition - (Age > 35)
'Dim filterOne As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35)
'PrintOnConsole(filterOne, "2. --- Filtering List<T> on single condition (Age > 35) ---")
''
'' Filtering List(T) on multiple conditions (Age > 35 and Sex is Female)
'Dim filterMultiple As List(Of Person) = pList.FindAll(Function(p As Person) p.Age > 35 AndAlso p.Sex = "F"c)
'PrintOnConsole(filterMultiple, "3. --- Filtering List<T> on multiple conditions (Age > 35 and Sex is Female) ---")
''
''Sorting List(T) (Sort on FirstName)
'Dim sortFName As List(Of Person) = pList
'sortFName.Sort(Function(p1 As Person, p2 As Person) p1.FirstName.CompareTo(p2.FirstName))
'PrintOnConsole(sortFName, "4. --- Sort List<T> (Sort on FirstName) ---")
'
'Sorting List(T) descending (Sort on LastName descending)
'Dim sortLNameDesc As List(Of Person) = pList
'sortLNameDesc.Sort(Function(p1 As Person, p2 As Person) p2.LastName.CompareTo(p1.LastName))
'PrintOnConsole(sortLNameDesc, "5. --- Sort List<T> descending (Sort on LastName descending) ---")
''Add new List(T) to existing List(T)
'Dim newList As List(Of Person) = New List(Of Person)()
'newList.Add(New Person(16, "Geoff", "", "Fisher", 29, "M"c))
'newList.Add(New Person(17, "Samantha", "Carl", "Baxer", 32, "F"c))
'pList.AddRange(newList)
'PrintOnConsole(pList, "6. --- Add new List<T> to existing List<> ---")
''Remove multiple items from List(T) based on condition (remove male employees)
'Dim removeList As List(Of Person) = pList
'removeList.RemoveAll(Function(p As Person) p.Sex = "M"c)
'PrintOnConsole(removeList, "7. --- Remove multiple items from List<> based on condition ---")
'' Create Read Only List(T)
'Console.WriteLine("Create Read Only List<>")
'Dim personReadOnly As IList(Of Person) = pList
'Console.WriteLine("Before - Is List Read Only? True or False : " & personReadOnly.IsReadOnly)
'personReadOnly = pList.AsReadOnly()
'Console.WriteLine("After - Is List Read Only? True or False : " & personReadOnly.IsReadOnly & "</br>")
'
'Dim pList1 As New Person
Dim emp As New List(Of Employee)
Dim r As New Employee
r.CompanyName = "zac"
r.Office = "home"
r.Empoyee_ID = 1
'Dim pList1 = New Person(1, "John", "", "Shields", 29, "M"c)
r.colPerson.Add(New Person(1, "John", "", "Shields", 29, "M"c))---> Gives error
emp.Add(r)
'
Dim i As New Employee
i.CompanyName = "zac1"
i.Office = "home1"
i.Empoyee_ID = 2
i.colPerson.Add(New Person(3, "Amber", "Carl", "Agar", 25, "M"c))
pList.Add(New Person(4, "Kathy", "", "Berry", 21, "F"c))
emp.Add(i)
'
Dim t As New Employee
t.CompanyName = "zac2"
t.Office = "home2"
t.Empoyee_ID = 2
pList.Add(New Person(5, "Lena", "Ashco", "Bilton", 33, "F"c))
pList.Add(New Person(6, "Susanne", "", "Buck", 45, "F"c))
emp.Add(t)
For Each item In emp
'item.CompanyName = "zac"
'item.Office = "home"
'item.colperson.Where(Function(x) x.ID = 17)
'Console.WriteLine("employee with person collection: " & item.CompanyName & " " & item.Office & " " & item.colperson.Where(Function(x) x.ID = 17).ToString & "</br>")
Console.WriteLine("employee with person collection: " & item.CompanyName & " " & item.Office & "</br>")
Next
End Sub
r.colPerson.Add(New Person(1, "John", "", "Shields", 29, "M"c))---> Gives error
It gives an error because even though colPerson is declared to be capable of holing a list of people, it hasn't actually been set to be a list of people, so it's currently Nothing, and you can't call methods on something that is Nothing
Property colPerson As New List(Of Person)
^^^
Add a New directive to ensure it's declared and initialized to an instance of a List
Also, please:
Don't put "col" in names
Use a plural name for List(Of Thing) - this is a list of person so it should at least be called People, but also perhaps state what kind of people they are. For example if this Employee was recommended by a few people, call it RcommendedByPeople
Only use Collection in a name if you're writing a class that is a collection, such as Microsoft did when they wrote MatchCollection - a collection of regular expression Matches
Be definite about whether the property is public, private etc
i.e.
Public Property RcommendedByPeople As New List(Of Person)
I have a list box and the user is able to multi-select. I want to use Linq and bring back the records of the selected IDs that the user selects. I need to bring back the full object record for each selected ID
Here is the contact object along with collection object
Namespace MODEL
<System.Serializable()> _
Public Class ContactCollection
Inherits System.Collections.ObjectModel.Collection(Of Contact)
Implements IList(Of Contact)
End Class
End Namespace
Namespace MODEL
<System.Serializable()> _
Public Class Contact
Private mContactID As Int32 = 0
Private mFirstName As String
Private mLastName As String
Public Property ContactID As Int32
Get
Return mContactID
End Get
Set(value As Int32)
mContactID = value
End Set
End Property
Public Property FirstName As String
Get
Return mFirstName
End Get
Set(value As String)
mFirstName = value
End Set
End Property
Public Property LastName As String
Get
Return mLastName
End Get
Set(value As String)
mLastName = value
End Set
End Property
End Class
End Namespace
Adding 5 Records to the collection object
Dim objCollection As New MODEL.ContactCollection
Dim obj As New MODEL.Contact
objCollection.Add(New MODEL.Contact With {
.ContactID = 1, _
.FirstName = "John", _
.LastName = "Smtih" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 2, _
.FirstName = "Mark", _
.LastName = "Davis" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 3, _
.FirstName = "Tom", _
.LastName = "Howe" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 4, _
.FirstName = "Jerry", _
.LastName = "Thomas" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 5, _
.FirstName = "Jane", _
.LastName = "Marry" _
})
This is the selected contact List from the list box
Dim lstContacts As New List(Of Integer)
lstContacts.Add(2)
lstContacts.Add(4)
I am not sure what to do at this point with Linq to find the values. I think I have to use contains but I have tried may different ways but I was unable to get the values.
I have tried this Linq but does not work or bring any records back
Dim objSearch from SearchContacts in objCollection
Where (lstContacts.Contains(SearchContacts.ContactID))
To get the Ids, try that :
Dim ids As IEnumerable(Of Int32) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.Select( Function(c) c.ContactID ) _
Edit
If you want the Contacts, you can just just :
Dim ids As IEnumerable(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)()
And if you want the contacts in a separate copied collection, you can :
Dim ids As List(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.ToList()
Last (if think this is your real question - just tell and I erase everything above)
Dim selectedContacts As IEnumerable(Of MODEL.Contact) = From contact In objCollection
Join id In lstContacts
On contact.ContactID Equals id
Select contact
I am a newbie
I have problem with string builder. I want to show to Richtextbox in vb with Richtextbox template
i.e.
Jan 674 Meet 670 Missed 4
Feb 635 Meet 631 Missed 4
etc.
with source from datagirdview with 8 columns and xxxx rows.
for ex. columns are : Registered Date, Deadline Date, Month, Meet/Not Meet,etc.
This my Code :
For Each keyvalue As KeyValuePair(Of String, Integer) In DicMonth
sb.AppendLine(String.Format("{0} : {1}", UCase(keyvalue.Key), keyvalue.Value))
Next
For Each keyvalue1 As KeyValuePair(Of String, Integer) In DicMeetTotal
sb.AppendLine(String.Format("{0}", "MEET : " & keyvalue1.Value))
Next
RichTextBox2.Text = sb.ToString
and the result is :
Jan : 674
Feb : 635
Mar : 623
Meet : 670
Meet : 631
Meet : 621
Missed : 4
Missed : 4
Missed : 2
Assuming the same order and length of dictionaries, you can use Zip to stitch the two dictionaries together:
Sub Main
Dim sb = New StringBuilder()
Dim DicMonth = New Dictionary(Of String, Integer)() From { _
{"Jan", 674}, _
{"Feb", 635} _
}
Dim DicMeetTotal = New Dictionary(Of String, Integer)() From { _
{"Jan", 670}, _
{"Feb", 631} _
}
Dim lineStrings = DicMonth.Zip(DicMeetTotal, _
Function(m, mt) String.Format("{0} {1} Meet {2} Missed {3}", _
m.Key, m.Value, mt.Value, m.Value - mt.Value))
For Each ls In lineStrings
sb.AppendLine(ls)
Next
Console.WriteLine(sb.ToString())
End Sub
Alternatively, if there is a join key (e.g. the Key value in both dictionaries is the same), you can use Linq Join them together, like so:
Dim lineStrings = DicMonth.Join(DicMeetTotal, _
Function(m) m.Key, Function(mt) mt.Key, _
Function(m, mt) String.Format("{0} {1} Meet {2} Missed {3}", _
m.Key, m.Value, mt.Value, m.Value - mt.Value))
Edit
Assuming that you wouldn't have modelled N different dictionaries each containing just a single value (this would be a modelling error along the lines of Entity Attribute Value, IMO), I'm guessing you'll want an entity to hold the data:
Class MeetTotalEntity
Public Property Meet As Integer
Public Property Missed As Integer
Public Property Cancel As Integer
Public Property Other As Integer
End Class
And then the Zip (or Join) still holds. The Value of the second dictionary contains the above entity, so just dereference the fields accordingly.
Sub Main
Dim sb = New StringBuilder()
Dim DicMonth = New Dictionary(Of String, Integer)() From { _
{"Jan", 674}, _
{"Feb", 635} _
}
Dim DicMeetTotal = New Dictionary(Of String, MeetTotalEntity)() From { _
{"Jan", New MeetTotalEntity With {.Meet = 670, .Missed = 4, .Cancel = 10, .Other = 5}}, _
{"Feb", New MeetTotalEntity With {.Meet = 631, .Missed = 10, .Cancel = 3, .Other = 2}} _
}
Dim lineStrings = DicMonth.Zip(DicMeetTotal, _
Function(m, mt) String.Format("{0} Total {1} Meet {2} Missed {3} Cancel {4} Other {5}", _
m.Key, m.Value, mt.Value.Meet, mt.Value.Missed, mt.Value.Cancel, mt.Value.Other))
For Each ls In lineStrings
sb.AppendLine(ls)
Next
Console.WriteLine(sb.ToString())
End Sub
I have two CheckboxLists. Based on the items checked, the checked values are concatenated into a comma separated string and passed to my entity framework method. The result would be a List(Of Entity).
I want to convert
SELECT *
FROM dbo.Findings /*Below criteria is added only if any of the values are checked*/
WHERE FindingCategoryId IN (<Checked Values>)
AND FindingSeverityId IN (<CheckBoxValues>)
I am unable to find an equivalent for IN for VB.Net in EF.
I looked at the C# post here and came up with the below code. I get an error as
Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
How can I use the IN clause in Vb.Net? Any help is appreciated.
My code:
Public Function Findings(ByVal findingSeverity As String, ByVal findingCategory As String) As List(Of Finding)
Dim aTypeLoanId As Integer = If(Not IsNothing(AuditTypeLoanId), AuditTypeLoanId, -1)
Dim findingTargetId = CInt(FindingTarget.LoanHeader)
Using e As New LQCEntities()
Dim result = (From f In e.FindingEntities _
From hmd In e.HeaderMetaDataEntities.Where(Function(h) h.MetaDataId = f.TargetId).DefaultIfEmpty() _
From cl In e.CheckListEntities.Where(Function(c) c.CheckListId = f.TargetId).DefaultIfEmpty() _
Where f.AuditTypeLoanId = aTypeLoanId _
Select New Finding With _
{
.FindingId = f.FindingId, _
.FindingCategoryId = f.FindingCategoryId, _
.FindingSeverityId = f.FindingSeverityId, _
.EnteredBy = f.ADUser.DisplayName, _
.EnteredDate = f.EnteredDate _
})
Dim fsArray() = Nothing
Dim fcArray() = Nothing
If (Not String.IsNullOrEmpty(findingSeverity)) Then
Dim fs = findingSeverity.Split(",")
For i As Integer = 0 To fs.Count - 1
Dim j As Integer = 0
If (Integer.TryParse(fs(i), j)) Then
ReDim Preserve fsArray(i)
fsArray(i) = j
End If
Next
If (fsArray.Count > 0) Then
result = result.Where(Function(i) fsArray.Contains(i.FindingSeverityId))
End If
End If
If (Not String.IsNullOrEmpty(findingCategory)) Then
Dim fc = findingCategory.Split(",")
For i As Integer = 0 To fc.Count - 1
Dim j As Integer = 0
If (Integer.TryParse(fc(i), j)) Then
ReDim Preserve fcArray(i)
fcArray(i) = j
End If
Next
If (fcArray.Count > 0) Then
result = result.Where(Function(i) fcArray.Contains(i.FindingCategoryId))
End If
End If
Return result.ToList()
End Using
End Function
I changed the fsArray and fcArray to a List(Of Integer) and it worked.
Code is as below:
Public Function Findings(ByVal findingSeverity As String, ByVal findingCategory As String) As List(Of Finding)
Dim aTypeLoanId As Integer = If(Not IsNothing(AuditTypeLoanId), AuditTypeLoanId, -1)
Dim findingTargetId = CInt(FindingTarget.LoanHeader)
Using e As New LQCEntities()
Dim result = (From f In e.FindingEntities _
From hmd In e.HeaderMetaDataEntities.Where(Function(h) h.MetaDataId = f.TargetId).DefaultIfEmpty() _
From cl In e.CheckListEntities.Where(Function(c) c.CheckListId = f.TargetId).DefaultIfEmpty() _
Where f.AuditTypeLoanId = aTypeLoanId _
Select New Finding With _
{
.FindingId = f.FindingId, _
.AuditTypeLoanId = f.AuditTypeLoanId, _
.FindingCategoryId = f.FindingCategoryId, _
.CategoryDescription = f.FindingCategory.CategoryDescription, _
.FindingSeverityId = f.FindingSeverityId, _
.SeverityDescription = f.FindingSeverity.SeverityDescription, _
.TargetId = f.TargetId, _
.UserResponse = f.UserResponse, _
.Field = If(f.FindingTargetId = findingTargetId, hmd.ColumnDescription, cl.CheckListDesc), _
.OldValue = f.OldValue, _
.NewValue = f.NewValue, _
.Comments = f.Comments, _
.EnteredBy = f.ADUser.DisplayName, _
.EnteredDate = f.EnteredDate _
})
If (Not String.IsNullOrEmpty(findingSeverity)) Then
Dim fsList As New List(Of Integer)
Dim fs = findingSeverity.Split(",")
For i As Integer = 0 To fs.Count - 1
Dim j As Integer = 0
If (Integer.TryParse(fs(i), j)) Then
fsList.Add(j)
End If
Next
If (fsList.Count > 0) Then
result = result.Where(Function(i) fsList.Contains(i.FindingSeverityId))
End If
End If
If (Not String.IsNullOrEmpty(findingCategory)) Then
Dim fc = findingCategory.Split(",")
Dim fcList As New List(Of Integer)
For i As Integer = 0 To fc.Count - 1
Dim j As Integer = 0
If (Integer.TryParse(fc(i), j)) Then
fcList.Add(j)
End If
Next
If (fcList.Count > 0) Then
result = result.Where(Function(i) fcList.Contains(i.FindingCategoryId))
End If
End If
Return result.ToList()
End Using
End Function
I am trying to sort a list by company name. I have tried the following code but this sorts the list by CompID and not CoShort. How should I change this to sort by CoShort?
Public Shared Function [SelectCompanyData](iElement() As Integer) As List(Of CompanyList)
Dim db As New EntryDataContext()
Dim q As IQueryable(Of CompanyList) = (From Act_Sub_Manfu_Link In db.Act_Sub_Manfu_Links _
Join Company In db.Companies _
On Act_Sub_Manfu_Link.CompID Equals Company.CompID _
Where iElement.Contains(Act_Sub_Manfu_Link.ACCN) _
And Company.In_Dir _
Select New CompanyList With { _
.CompID = Company.CompID, _
.InDir = Company.In_Dir, _
.CoShort = Company.CoShort _
}).Distinct
q.OrderBy(Function(c) c.CoShort)
Dim list As List(Of CompanyList) = q.ToList
Return list
End Function
You have to assign ordered collection into a variable:
Dim oq As IOrderedQueryable(Of CompanyList) = q.OrderBy(Function(c) c.CoShort)
And use it to get List of results:
Dim list As List(Of CompanyList) = oq.ToList()
Doesn't need to be assigned to anything but the return value
Public Function SelectCompanyData(iElement() As Integer) As List(Of CompanyList)
Dim db As New EntryDataContext()
Return (From Act_Sub_Manfu_Link In db.Act_Sub_Manfu_Links _
Join Company In db.Companies _
On Act_Sub_Manfu_Link.CompID Equals Company.CompID _
Where iElement.Contains(Act_Sub_Manfu_Link.ACCN) _
And Company.In_Dir _
Select New CompanyList With { _
.CompID = Company.CompID, _
.InDir = Company.In_Dir, _
.CoShort = Company.CoShort _
}).Distinct().OrderBy(Function(c) c.CoShort).ToList()
End Function