Conversion between collection interface types

S

satyajit

Hi All,

I have a class that has a property returning IList. For example,

class A
{
public IList<string> MyList
{
get { return _list; }
set { _list = new List<string>(value); }
}

private List<string> _list;
}

Now, I have a method that has an IEnumerable and tries to set MyList
property of an object of type A. Here is how I have done it:

void f(A a, IEnumerable<string> list)
{
a.MyList = new List<string>(list);
}

The above works fine, but I think there must be a better way to
achieving this rather than create temporary List<string> objects. This
happens twice - 1) While converting from IEnumerable<> to IList<>, and
2) While converting from IList<> to List<> Last thing I would want is
to change the return type of the property or the signature of f(). Any
suggestions?

On side notes, how bad is it performance wise?

- Satyajit
 
J

Jon Skeet [C# MVP]

The above works fine, but I think there must be a better way to
achieving this rather than create temporary List<string> objects. This
happens twice - 1) While converting from IEnumerable<> to IList<>, and
2) While converting from IList<> to List<> Last thing I would want is
to change the return type of the property or the signature of f(). Any
suggestions?

Two options:

1) Have an extra setter in A which takes an IEnumerable<string>
2) Create a lightweight implementation of IList<T> which accepts (and
retains) an IEnumerable<T> and does the bare minimum needed by the List
On side notes, how bad is it performance wise?

Well, it'll be at least O(n), but possibly worse because of the copying
that will occur when the internal buffer fills up. Unfortunately I'm
too tired to work out whether that makes it O(n log n) or O(n^2). The
former, I suspect, because the copying will only happen O(log n) times
assuming the internal buffer size goes up proportionally (eg doubling)
rather than linearly.
 
S

satyajit

Two options:

1) Have an extra setter in A which takes an IEnumerable<string>

Do you mean that I write one more property (say MyList1) that takes an
IEnumerable said:
2) Create a lightweight implementation of IList<T> which accepts (and
retains) an IEnumerable<T> and does the bare minimum needed by the List
<T> constructor.

Would any of the classes provided by the .NET class library (closest)
fit in here?

Thanks.
 
J

Jon Skeet [C# MVP]

satyajit said:
Do you mean that I write one more property (say MyList1) that takes an
IEnumerable<>?

I wouldn't write a whole extra property - just a single method.
Would any of the classes provided by the .NET class library (closest)
fit in here?

I don't know of any, I'm afraid.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top