How to concatenate ReadOnlyCollection

5.8k Views Asked by At

The ReadOnlyCollection constructor requires that you give it IList. But if you have some ROC's that you want to concatenate and produce a new ROC, the Concat method returns IEnumerable. Which is not a valid argument to pass to the ROC constructor.

So how do you create a ROC as the concatenation of other ROC's?

So far, this is the best I can come up with:

ReadOnlyCollection<T> ROCConcat<T> ( ReadOnlyCollection<T> a, ReadOnlyCollection<T> b)
{
    List<T> tmp = new List<T>();
    foreach (T f in a.Concat(b))
        tmp.Add(f);
    return new ReadOnlyCollection<T>(tmp);
}
2

There are 2 best solutions below

2
On BEST ANSWER

I believe you can use ReadOnlyCollectionBuilder to do this.

return (new ReadOnlyCollectionBuilder<T>(a.Concat(b))).ToReadOnlyCollection();
2
On

Create a new List<> out of your IEnumerable<>:

return new ReadOnlyCollection<T>(a.Concat(b).ToList());

Or I prefer:

return a.Concat(b).ToList().AsReadOnly();

These basically do the same thing as what you've come up with, but they're a little easier on the eyes.