Question

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);
}
Était-ce utile?

La solution 2

I believe you can use ReadOnlyCollectionBuilder to do this.

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top