1
\$\begingroup\$

I'm using VB.Net, MVC 5, EF 6, and Linq. I have a list of Integers (category attribute IDs). I need to create a second list of String (values). There will be one string for each integer.

I am currently accomplishing my task like this:

Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)
 Dim db As New Model1
 Dim values = New List(Of String)
 For i As Integer = 0 To catAttIDs.Count - 1
 Dim catAttID = catAttIDs(i)
 Dim currentValue = (From row In db.tblEquipment_Attributes
 Where row.Category_Attribute_Identifier = catAttID _
 And row.Unique_Item_ID = itemID
 Select row.Value).SingleOrDefault()
 values.Add(currentValue)
 Next
 Return values
End Function

I have a strong feeling that there is a better way to do this, but I have not been able to find the information I'm looking for.

I'm particularly interested in changing this code so that the database is called once for the list, instead of calling the database 5 or 6 times as I work my way through the list.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 7, 2015 at 16:08
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You're looking for the LINQ-equivalent of an IN clause in SQL. So something like this:

SELECT value FROM tblEquipment_Attributes 
WHERE Category_Attribute_Identifier IN (<list of integers>) 
AND Unique_Item_ID = itemID;

So what you could do is write your LINQ statement to see if the Category_Attribute_Identifier is in the list. Then your function will look something like this:

Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)
 Dim db As New Model1
 Dim currentValues as List(Of String) = (From row In db.tblEquipment_Attributes
 Where catAttIDs.Contains(row.Category_Attribute_Identifier) _
 And row.Unique_Item_ID = itemID
 Select row.Value).ToList()
 Return currentValues
End Function

Note that ToList will create a List<T>, where T is the type of the elements. As long as Value in your db is a varchar, it'll be a List.

answered Oct 7, 2015 at 20:27
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.