combine ReadOnlyCollection(of String)

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
can you combine 2 readonlycollection(of string) ? I tried Directcast(a.union(b),objectmodel.readonlycollection(of string)) but that give me error on casting. Do i need to conect it to an array first?
 
Firstly, what do you mean by combine? You are using Union, which is a set operation. Is that what you want, or do you actually want Concat? As an example, if the first list contains {1, 2, 3, 1} and the second list contains {1, 3, 5} then the result of a Union will be {1, 2, 3, 5} while the result of a Concat will be {1, 2, 3, 1, 1, 3, 5}.

As for combining them, Union or Concat will return an IEnumerable(Of String), just as any LINQ query would (Union and Concat are part of LINQ). If you just want to use that result once than you can probably use it as is, e.g. enumerate it with a For Each loop. If you want to keep the list around for random access then, just like with any other LINQ query, you must call its ToArray or ToList method to produce a String() or List(Of String) respectively. If you specifically want a ReadOnlyCollection(Of String) then you have to create a new one. It has a constructor that takes any IList(Of String), so it will accept the result of ToArray or ToList. In choosing to call ToArray or ToList, ToArray should always be your default choice and you should only ever call ToList if you specifically need a List. In this case you don't specifically need a List so call ToArray. E.g.
Dim c As New ReadOnlyCollection(Of String)(a.Union(b).ToArray())
 
Back
Top