Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate ReadOnlyCollection

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);
}
like image 698
Edward Ned Harvey Avatar asked Jan 02 '14 20:01

Edward Ned Harvey


2 Answers

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.

like image 89
StriplingWarrior Avatar answered Nov 01 '22 09:11

StriplingWarrior


I believe you can use ReadOnlyCollectionBuilder to do this.

return (new ReadOnlyCollectionBuilder<T>(a.Concat(b))).ToReadOnlyCollection();
like image 7
Brian Reischl Avatar answered Nov 01 '22 08:11

Brian Reischl