How to add a character to the beginging of each string in a list of strings - vb.net

I have a simple list of strings and what i need to do is to add "#" to the beginning of each item and join the list to get something like: "#item1, #item2,...."
my code so far:
Dim list As New List(Of String)({"item1", "item2", "item3", "item4"})
' create a copy of list to prevent altering it
Dim listCopy As List(Of String) = list
For i As Integer = 0 To listCopy.Count - 1
list(i) = "#" & listCopy(i)
Next
Dim result As String = String.Join(", ", list.ToArray())
While this does the job but i feel that it's too much code for a simple function, the same thing can be done in python or javascript much easier like:
python:
copyList = [("#" + x) for x in list]
javascript:
copylist = list.map(function(x){return '#' + x})
Is there a similar function in vb.net?

Yes, you can use the LINQ Select method to achieve this:
Dim list As New List(Of String)({"item1", "item2", "item3", "item4"})
dim list1 = list.Select(function (i) "#" + i)
for each item in list1
Console.WriteLine(item)
next item
And the output is:
#item1
#item2
#item3
#item4
The result is an IEnumerable (Of String) object. If you want again a List (Of String) than use the ToList() extension method:
dim list1 = list.Select(function (i) "#" + i).ToList()

Use LINQ:
Dim result = (From s In list Select "#" & s)

Related

Linq How to combine List Items to other List items

I have multiple list of string with some items
want to combine every items together like below
Dim _rsltitm = Nothing
For Each _itm1 In _lst1
For Each _itm2 In _lst2
For Each _itm3 In _lst3
_rsltitm &= vbNewLine & _itm1 + _itm2 + _itm3
Next
Next
Next
above code is working fine but i have more than 8 lists or sometimes 11
so i need linq to combine multiple list of string items together
i am trying like this but i could not
Dim _rslt = From itm In _lst1 Select (Function(x) From itm2 In _lst2 Select (Function(d) x & d))
I just tested this code and it seems to do what you want:
Dim list1 As New List(Of String) From {"1", "2", "3"}
Dim list2 As New List(Of String) From {"A", "B", "C"}
Dim list3 As New List(Of String) From {"7", "8", "9"}
Dim list4 As New List(Of String) From {"X", "Y", "Z"}
Dim lists = {list1, list2, list3, list4}
Dim result = lists.Aggregate(Function(current, list)
Dim combinedList As New List(Of String)
For Each prefix In current
combinedList.AddRange(From suffix In list Select prefix & suffix)
Next
Return combinedList
End Function)
You just add all your lists to that lists array and result should end up containing the desired result.
I feel like that Lambda body should be able to be LINQified a bit more but my initial attempts didn't work so I gave up quickly. If you want to put some more time into it, you're welcome to.
EDIT:
Here's that in a function:
Private Function CombineLists(ParamArray lists As List(Of String)()) As List(Of String)
Return lists.Aggregate(Function(current, list)
Dim combinedList As New List(Of String)
For Each prefix In current
combinedList.AddRange(From suffix In list Select prefix & suffix)
Next
Return combinedList
End Function)
End Function
In my example, I could either call that like so:
Dim result = CombineLists(list1, list2, list3, list4)
or like so:
Dim lists = {list1, list2, list3, list4}
Dim result = CombineLists(lists)

Sum the repeated string list values and merge as one using linq in .net

The below code I tried to sum up the string value with the list values, it happens, but other values are not shown in return. I need to sum the values and other value should be returned to the object using linq in vb.net.
My code:
Dim lstrTaxValue As String = "YQ$40"
Dim lstaValues As New List(Of String)
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("PQ$8")
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("AQ$5")
Dim lobjTValues = (From lstr In lstaValues
From lval In lstrTaxValue.Split(" ")
Where (lstr.Split("$")(0) = CStr(lval).Split("$")(0))
Select (CStr(lval).Split("$")(0) & "$" & (CDbl(CStr(lval).Split("$")(1)) + CDbl(lstr.Split("$")(1))))).ToList()
What am I doing wrong?
To quote Jon Skeet...
Change some value inside the List<T>
In comments...
Why do you want to use lambda expressions? The foreach code works fine and is simple. LINQ is for querying data, not mutating it. – Jon Skeet
Your objective does not seem to lend itself to Linq.
Private Sub OPCode()
Dim lstrTaxValue As String = "YQ$40"
Dim lstaValues As New List(Of String)
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("PQ$8")
lstaValues.Add("YQ$10")
lstaValues.Add("TQ$3")
lstaValues.Add("AQ$5")
Dim TaxValue = lstrTaxValue.Split("$"c)
For i = 0 To lstaValues.Count - 1
If lstaValues(i).Split("$"c)(0) = TaxValue(0) Then
lstaValues(i) = TaxValue(0) & "$" & CStr(CDbl(lstaValues(i).Split("$"c)(1)) + CDbl(TaxValue(1)))
End If
Next
For Each s In lstaValues
Debug.Print(s)
Next
End Sub
Result:
YQ$50
TQ$3
PQ$8
YQ$50
TQ$3
AQ$5

VB.net Dictionary loop

Hey all i am in need of some help looping thru my Dictionary list. I can not seem to find the correct syntax in order to do so.
Here is my code:
Dim all = New Dictionary(Of String, Object)()
Dim info = New Dictionary(Of String, Object)()
Dim theShows As String = String.Empty
info!Logo = channel.SelectSingleNode(".//img").Attributes("src").Value
info!Channel = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(0).InnerText
info!Station = .SelectSingleNode("channel.//span[#class='channel']").ChildNodes(1).ChildNodes(2).InnerText
info!Shows = From tag In channel.SelectNodes(".//a[#class='thickbox']")
Select New With {channel.Show = tag.Attributes("title").Value, channel.Link = tag.Attributes("href").Value}
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows") '<--Doesnt work...
I just want to extract whatever is in "Shows" from the all dictionary.
Your code,
all.Add(info!Station, info.Item("Shows"))
theShows = all.Item("Shows")
The value of info!Station is being used as the KEY value in the all dictionary. Then you attempt to access the value using the constant string "Shows". I'm not sure what your intention was but
theShows = all.Item(info!Station)
should return the value of Shows that was stored using the Key info!Station.
If you want the list of shows as a string, you can do this,
Dim Shows as String = ""
For Each item in theShows
Shows &= item.Show & vbNewLine
Next
You can loop like this
For Each pair As KeyValuePair(Of String, String) In dict
MsgBox(pair.Key & " - " & pair.Value)
Next
source : VB.Net Dictionary
Winston

String Array Thing!

Right - to start with, I'm entering unfamiliar areas with this - so please be kind!
I have a script that looks a little something like this:
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
Dim strOut As String = ""
Dim strWord As String
For Each strWord In astrWords
If strIn.ToLower.IndexOf(strWord.ToLower, 0) >= 0 Then
strOut = strWord.ToLower
Exit For
End If
Next
Return strOut
End Function
It's function is to check the input string and see if any of those 'astrWords' are in there and then return the value.
So I wrote a bit of code to dynamically create those words that goes something like this:
Dim extensionArray As String = ""
Dim count As Integer = 0
For Each item In lstExtentions.Items
If count = 0 Then
extensionArray = extensionArray & """." & item & """"
Else
extensionArray = extensionArray & ", ""." & item & """"
End If
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Obviously - it's creating that same array using list items. The output of that code is exactly the same as if I hard coded it - but when I change the first bit of code to:
Dim astrWords As String() = New String() {My.Settings.extensionArray}
instead of:
Dim astrWords As String() = New String() {"bak", "log", "dfd"}
It starts looking for the whole statement instead of looping through each individual one?
I think it has something to do with having brackets on the end of the word string - but I'm lost!
Any help appreciated :)
When you use the string from the settings in the literal array, it's just as if you used a single strings containing the delimited strings:
Dim astrWords As String() = New String() {"""bak"", ""log"", ""dfd"""}
What you probably want to do is to put a comma separated string like "bak,log,dfd" in the settings, then you can split it to get it as an array:
Dim astrWords As String() = My.Settings.extensionArray.Split(","C)
You need to set extensionArray up as a string array instead of simply a string.
Note that
Dim something as String
... defines a single string, but
Dim somethingElse as String()
... defines a whole array of strings.
I think with your code, you need something like:
Dim extensionArray As String() = new String(lstExtensions.Items)
Dim count As Integer = 0
For Each item In lstExtentions.Items
extensionArray(count) = item
count = count + 1
Next
My.Settings.extensionArray = extensionArray
My.Settings.Save()
Then at the start of checkString you need something like
Private Function checkString(ByVal strIn As String) As String
Dim astrWords As String() = My.Settings.extensionArray
...
There also might be an even easier way to turn lstExtentions.Items into an Array if Items has a 'ToArray()' method, but I'm not sure what Type you are using there...
What you've done is created a single string containing all 3 words. You need to create an array of strings.
New String() {"bak", "log", "dfd"}
means create a new array of strings containing the 3 strings values "bak", "log" and "dfd".
New String() {My.Settings.extensionArray}
means create a new array of strings containing just one value which is the contents of extensionArray. (Which you have set to ""bak", "log", "dfd""). Note this is one string, not an array of strings. You can't just create 1 string with commas in it, you need to create an array of strings.
If you want to create your array dynamically, you need to define it like this:
Dim astrWords As String() = New String(3)
This creates an array with 3 empty spaces.
You can then assign a string to each space by doing this:
astrWords(0) = "bak"
astrWords(1) = "log"
astrWords(2) = "dfd"
You could do that bit in a for loop:
Dim count As Integer = 0
For Each item In lstExtentions.Items
astrWords(count) = item
count = count + 1
Next
Alternatively, you could look at using a generic collection. That way you could use the Add() method to add multiple strings to it
I think you want your extensionArray to be of type String() and not String. When you are trying to initialize the new array, the initializer doesn't know to parse out multiple values. It just sees your single string.

How can I search an array in VB.NET?

I want to be able to effectively search an array for the contents of a string.
Example:
dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}
I pass the value is "ra" and I want it to return the index of 2 and 3.
How can I do this in VB.NET?
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.
In case you were looking for an older version of .NET then use:
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result As New List(Of Integer)
For i As Integer = 0 To arr.Length
If arr(i).Contains("ra") Then result.Add(i)
Next
End Sub
End Module
check this..
string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
Array.IndexOf(strArray, "C"); // not found, returns -1
Array.IndexOf(strArray, "CDE"); // found, returns index
compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.
simple eg.
dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)
if aNames(x) = sFind then y = x
y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:
z = 1
for x = 1 to length(aNames)
if aNames(x) = sFind then
aIndexes(z) = x
z = z + 1
endif
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Never use .ToLower and .ToUpper.
I just had problems in Turkey where there are 4 "i" letters. When using ToUpper I got the wrong "Ì" one and it fails.
Use invariant string comparisons:
Const LNK as String = "LINK"
Dim myString = "Link"
Bad:
If myString.ToUpper = LNK Then...
Good and works in the entire world:
If String.Equals(myString, LNK , StringComparison.InvariantCultureIgnoreCase) Then...
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))