List<T>, Collection<T>, and FindAll

  • Thread starter David Longnecker
  • Start date
D

David Longnecker

I'm working to create a base framework for our organization for web and client-side
applications. The framework interfaces with several of our systems and provides
the business and data layer connectivity for basic operations and such.

I've ran into a snag that I just can't think myself out of.

Here's an example:

I have an object for a Student called StudentRecord. It has properties such
as name, grade, identification number, etc.

public class StudentRecord : IComparable
{

private int _studentId;
public int StudentId { get { return _studentId; } set { _studentId = value;
} }

public override string ToString() { get { return string.Format("{0} {1}",
_firstName, _lastName); }

... etc.

}

From there, I have a "roster" of students, thus a collection of those StudentRecord
objects. I would like to inherit from List<StudentRecord> to provide Find,
FindAll, Sort, and other functionality to the consumer of the API. (1)*

public class StudentRoster : List<StudentRecord>
{
// I'm not providing any additional functionality here at this time,
// simply providing the easier call rather than requring them to know List<object>.
}

Now, roster.Find works just fine because, I'm assuming, the list is based
off StudentRecord.

StudentRecord studentA = roster.Find(delegate(StudentRecord x) { return x.LastName.Equals("Longnecker");
});

This returns me a populated student object based off a prior created collection
of student Objects.

I run into an issue with:

StudentRoster studentsInGrade8 = roster.FindAll(delegate (StudentRecord x)
{ return x.Grade.Equals("08"); } );

FindAll apparently returns a raw list of List<StudentRecord> rather than
StudentRoster (since I haven't specified it). I've attempted to modify my
StudentRoster class to add:

public StudentRoster FindAll(Predicate<StudentRecord> item)
{

StudentRoster items = (StudentRoster) Items;
return items.FindAll(match);

}

However, that fails with the same error--it cannot convert List<StudentRecord>
to StudentRoster. I've attempted to cast it explicitly (using 'as StudentRoster'
and (StudentRoster)) to no avail.

Google hasn't turned up anything thus far and neither has MSDN (though I'm
assuming, perhaps, I'm not searching for the magical word)... What would
be the best way to create "collections of objects" that can be searched through
using Find at the public API level?

(1)* == Note that CLS does specify not to expose List<T>; however, Collection<T>
doesn't have Find, Sort, FindAll, etc. Is there a better option?

Any reference material, etc. would be greatly appreciated!

Thanks in advance.

-dl
 
N

Nicholas Paldino [.NET/C# MVP]

David,

You are going to have to do an explicit copy here.

Assuming you don't want to hide the FindAll method (I recommend against
it), and that you expose the constructor for your StudentRoster which takes
an IEnumerable<StudentRecord>, you can do this:

StudentRoster studentsInGrade8 = new StudentRoster(roster.FindAll(delegate
(StudentRecord x) { return x.Grade.Equals("08"); } ));

This way, the List<StudentRecord> feeds the construction of the new
StudentRoster instance.

If you really want to return a StudentRoster instance, then I would
recommend creating a static FindAll method which will take the
IList<StudentRecord> implementation and then perform the conversion to a
StudentRoster instance yourself.

Hope this helps.
 
D

David Longnecker

Okay, wow, it hadn't even occured to me that the reference was just sorta
trying to override itself rather than create a new one--I've been staring
at this for too long today. Thanks.

So, I added two lines to my StudentRoster class. One, the IEnumerable for
creating new, and the empty one:

public class StudentRoster : List<StudentRecord>, IEnumerable
{
public StudentRoster(IEnumerable<StudentRecord> record) : base (new
List<StudentRecord>(record)) { }
public StudentRoster() : base(new List<StudentRecord>()) { }

}

Then, as you said, the new roster works:

StudentRoster studentsInGrade9 = new StudentRoster(roster.FindAll(delegate(StudentRecord
x) { return x.Grade.Equals("09"); }));
Console.WriteLine("There are {0} students in the ninth grade.", studentsInGrade9.Count);

The follow up I have to that is that I'm not sure how to please both keepers,
so to speak. I'm wanting to propagate down the .Find, .FindAll, and .Sort
(for example) methods, but CLS (ala FxCop) is complaining that:

"Change %OBJECT% to use Collection<T>, ReadOnlyCollection<T>
or KeyedCollection<K,V>"

Of course, Collection doesn’t have the methods of List. Is there a benefit
to this beyond 100% compliance? If so, is it documented out there ‘best
practices’ of how to create “collections that act like lists�

Thanks!

-dl
 
N

Nicholas Paldino [.NET/C# MVP]

David,

You don't have to add the IEnumerable interface declaration, List<T>
already does that for you.

Your class should look something like this:

public class StudentRoster : List<StudentRecord>
{
public StudentRoster(IEnumerable<StudentRecord> collection) :
base(collection)
{ }

public StudentRoster() : base()
{ }
}

There is no need for you to create a new list to pass to the base
constructor, since it is looking for an IEnumerable<T> (where T is
StudentRecord in this case) as well, you can just pass it directly.

And you also don't need to create a new instance and chain the
constructor for the default parameterless constructor, since you can just
call the base constructor of List<T>.

In order to please both keepers, you would have to derive from
Collection<T> like FxCop says. Of course, like you mention, it doesn't have
all the methods of List<T>, and you would have to implement those yourself.

You could try and create an explicit and implicit casting operator from
IEnumerable<StudentRecord> to StudentRoster, and that might get you a little
further, but personally, I find that feeding the constructor of a new
StudentRoster instance works fine for me. I can see what is happening, and
I'm not polluting the type (List<T>, from which you derive) so to speak.

This brings up an interesting point. If you are not adding any
significant functionality to List<StudentRecord> in the StudentRoster class,
then you really shouldn't be deriving from it. You aren't gaining anything
but a different name, and are gaining a headache in the process.
List<StudentRoster> seems to work just fine here (unless there is more to
the class than you are exposing here).

Another side note, LINQ is going to make all of this moot, since you
would be able to just do:

// Get the count of students in the 9th grade. I'm using your call to
Equals since I don't know what type the Grade property
// returns. If it was a string, I'd just use ==.
int count = (from student in roster where
student.Grade.Equals("09")).Count();

Once that happens, methods on collection types for searching, ordering,
etc, etc, are going to become pretty useless.
 
J

Jon Skeet [C# MVP]

On May 2, 2:24 pm, "Nicholas Paldino [.NET/C# MVP]" wrote:

Another side note, LINQ is going to make all of this moot, since you
would be able to just do:

// Get the count of students in the 9th grade. I'm using your call to
Equals since I don't know what type the Grade property
// returns. If it was a string, I'd just use ==.
int count = (from student in roster where
student.Grade.Equals("09")).Count();

Once that happens, methods on collection types for searching, ordering,
etc, etc, are going to become pretty useless.

I disagree. While LINQ has massive benefits in complex cases, just
using the extension methods (and existing methods) directly is
simpler. For instance, your query could be written equally effectively
as:

int count = roster.Count (student => student.Grade.Equals("09"));

Personally I'll save the compiler conversion stuff for more
complicated cases.

Jon
 
D

David Longnecker

Thanks for the information on IEnumerable and cutting that down a bit.

***
This brings up an interesting point. If you are not adding any
significant functionality to List<StudentRecord> in the StudentRoster
class, then you really shouldn't be deriving from it. You aren't
gaining anything but a different name, and are gaining a headache in
the process. List<StudentRoster> seems to work just fine here (unless
there is more to the class than you are exposing here).
***

You are correct; at this time, the derived class simply recreates List<StudentRecord>
with a more 'friendly' name of StudentRoster. I anticipate extending it
in the future, however, and didn't want to force any dependent applications
to have to change... I'd rather work out the issues now than later and still
require the consumers of the class to change their calls.

***
Another side note, LINQ is going to make all of this moot, since you would
be able to just do:
***

Agreed 100%; I wish the day was closer. As Jon S. points out (further down
the convo), I've dinked around with the lambda expressions on a copy of the
project in Orcas and it's more intuitive, or seem so, than the anonymous
methods.

Thanks for all your help and explainations; I don't feel my eyes crossing
(quite as bad) anymore. ;)

-dl
 

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