Is there a .NET equivalent of Java's List.subList()
that works on IList<T>
?
views:
886answers:
3
+3
A:
For the generic List<T>
, it is the GetRange(int, int)
method.
Edit: note that this is a shallow copy, not a 'view' on the original. I don't think C# offers that exact functionality.
Edit2: as Kamarey points out, you can have a read-only view:
List<int> integers = new List<int>() { 5, 6, 7, 8, 9, 10, 11, 12 };
IEnumerable<int> view = integers.Skip(2).Take(3);
integers[3] = 42;
foreach (int i in view )
// output
The above will print 7, 42, 9.
Razzie
2009-08-17 11:03:45
From the MSDN documentation (http://msdn.microsoft.com/en-us/library/21k0e39c.aspx) it doesn't seem to be the same: GetRange() returns a shallow copy, while subList() returns a view (i.e. changes to the subList() will be reflected in the original List!)
Joachim Sauer
2009-08-17 11:05:33
ok you're right. Not sure if this is the exact requirement, but I'll edit my answer to reflect that.
Razzie
2009-08-17 11:07:40
Again: it's not *exactly* the same thing, as it returns a shallow copy instead of a view. Returning a view enables some pretty nifty tricks (it makes it unnecessary to provide a RemoveRange() method for example, since it can easily be written as list.subList(x,y).clear()).
Joachim Sauer
2009-08-17 11:12:12
I must honestly say that I don't really see the benefits. Also, removeRange() and subList.clear() doesn't sound like the same thing, as clearing should not be the same as removing a range. But oh well :-)
Razzie
2009-08-17 11:14:13
As soon as you grok the concept that subList() returns a view into the original List (and not a copy), it will become obvious that someList.subList(1,3).clear() will remove objects from the original List. And the most important part is not if it's better or not, but that subList() and GetRange() don't do the same thing, so they shouldn't be presented as equivalent (at least not without a disclaimer).
Joachim Sauer
2009-08-17 11:21:04
ah of course, clear() removes contents as well. I thought it set its content to null or a default value or something.
Razzie
2009-08-17 11:48:16
@ripper234: there's a similar extension method, though it returns a read-only view. Not sure if that works for you, but see my updated answer.
Razzie
2009-08-17 11:51:50
Does this return a view into the original List or a copy of the range?
Joachim Sauer
2009-08-17 11:23:35
@Joachim Sauer: This is a query and it's result depends on how it's evaluated. While evaluating, it loops through list elements applying some rule. This isn't straight analog for Java's subList function, and it's mistake to compare them in this case.
Kamarey
2009-08-17 12:12:12
@Kamarey: fair enough, but then the solution should have a disclaimer to that effect. Generally it seems that there are ways to achieve what you want, but there's no single 1:1 match for subList() (which is not a problem, but it should be noted).
Joachim Sauer
2009-08-17 13:11:26