Solved

Working with Generics -- IList<T>

Posted on 2008-06-24
9
1,689 Views
Last Modified: 2013-12-16
Good evening experts:

My team is currently implementing an application that will manage a list of drugs.   To accomplish this task, we have implemented several data transfer objects to maintain these data.  One data transfer object, MyDrugList contains a single attribute of type List<DrugDetailDto> drug.   In this case, drug allows us to manage a list of drug objects .. add, remove, find, etc; however, upon submitting for code review, our enterprise architect pointed out a flaw in the development process and indicated we need not expose our List<T> objects:  ( http://msdn2.microsoft.com/en-us/library/ms182142(VS.80).aspx)

As an alternative, he suggested that we implement the IList interface to transfer objects between our layers.   I somewhat understand his requirement, but now some of our methods are not wanting to cooperate, which I've included below ..  

1) Could someone explain why this is an issue?
2) Could someone assist with how we can implement our search methods using these IList implementations?

We are using 2.0 Framework .. C#

Thanks,
Here is an example of where we search a DrugDetailDTO object for specific product data:
 

 /// <summary>//

        /// Extracts product information attached to a drug for a specified formulary

        /// </summary> 

        private DrugProductDTO GetProductDetail(DrugDetailDTO drug, string formularyID)

        {

            return drug.Products.Find(

                delegate(DrugProductDTO product)

                {

                    return product.ProductID.ToString().Equals(formularyID);

                }

                );

        }
 

AND
 

        /// <summary>

        /// Extracts Drugs information that has generics equivalents available

        /// </summary>

        private List<DrugDetailDTO> ExtractGenericsFromDrugList(List<DrugDetailDTO> myDrugList)

        {

            return myDrugList.FindAll(

                                      (

                                          delegate(DrugDetailDTO drug)

                                          {

                                              return drug.IsConvertibleToGenerics.Equals(true);
 

                                          }

                                      )

                                     );
 
 

        }
 

However, the find, findall, exists methods are not available with the IList interface.

Open in new window

0
Comment
Question by:escheider
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 11

Expert Comment

by:William
Comment Utility
Have you looked at:
http://blogs.msdn.com/fxcop/archive/2006/04/27/585476.aspx
?

Let me know if this helps


BillyDvd
0
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
So, why don´t return a Collection<> instead as suggested in the MSDN site?
Collection have the IList interface also.
What the article suggest is not to use List<> generic class.
0
 
LVL 6

Accepted Solution

by:
cottsak earned 250 total points
Comment Utility
you shouldnt have a MyDrugList object that exposes a List<T>. this is just some sort of container that should need to exist.
simply pass the List<DrugDetailDto> instances from layer to layer.
if the generic list (List<T>) search/find methods are not sufficient, then create a factory class that does the searching for you. ie:
List<DrugDetailDto> filteredResults = (new DrugDetailFactory()).Find(query);
you're custom logic would live in the Find() method above and return only the items in the list of the DrugDetailDto type that matched your query.. be that a string or maybe more params.. whatever.

below i have included some code to do in-memory filtering of generic lists. each entity item in the list must be able to expose all it's data as a string... so we override the ToString() method. i've done this by having the entity classes inherit from a Super Class which all entity classes use. this means they all have this functionality. - Snip#1
Snip#2 is a generic Filter class that returns filtered results based on the query string (filterExpression).
Snip#3 shows how i use this in a factory class for getting users... note that the filtering and sorting is optional. ignore the LINQ code if u want. :D

hope this helps. if u need more info just ask.
// Snip#1

        /// <summary>

        /// uses reflection to list public property info

        /// </summary>

        /// <returns></returns>

        public override string ToString()

        {

            string output = base.ToString() + " [" + this.GetHashCode() + "]" + Environment.NewLine;
 

            foreach (PropertyInfo property in this.GetType().GetProperties())

            {

                output += property.Name + ": "

                    + (property.GetValue(this, null) == null ? "null" : property.GetValue(this, null))

                    + Environment.NewLine;

            }
 

            return output;

        }
 
 
 

// Snip#2

    public class ListFilter<TEntity>

    {

        public List<TEntity> GetFilteredList(List<TEntity> list, string filterExpression)

        {

            List<TEntity> filteredResults = new List<TEntity>();

            int score = 0;

            string[] words = filterExpression.Trim().Split(' ');
 

            foreach (TEntity entity in list)

            {

                foreach (string word in words)

                    if (entity.ToString().ToLower().Contains(word.ToLower()))

                        score += 1;
 

                if (words.Length == score)

                    filteredResults.Add(entity);
 

                score = 0;

            }
 

            return filteredResults;

        }

    }
 
 
 

// Snip#3

    public class UserFactory : IRmsFactory<User, string>

    {

        public List<User> GetAll(string sortExpression, string filterExpression)

        {

            List<User> users = new List<User>();

            MembershipUserCollection allUsers = Membership.GetAllUsers();
 

            foreach (MembershipUser user in allUsers)

            {

                User u = new User();

                u.UserName = user.UserName;

                u.LastActivityDate = user.LastActivityDate;

                u.Roles = (new UserRoleFactory()).GetByUserName(user.UserName, String.Empty);

                users.Add(u);

            }
 

            // perform filtering before sort to reduce sort overhead if filter applied

            if (filterExpression != String.Empty && filterExpression != null)

                users = (new ListFilter<User>()).GetFilteredList(users, filterExpression);
 

            if (sortExpression != String.Empty && sortExpression != null)

                users.Sort(new EntityComparer<User>(sortExpression));
 

            return users;

        }

Open in new window

0
 
LVL 6

Expert Comment

by:cottsak
Comment Utility
EDIT (comment#21861988): there is no LINQ code there... that factory gets users from the Membership provider. other classes in that project used LINQ. sorry to confuse.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 4

Author Comment

by:escheider
Comment Utility
I can't pass the List<T> from layer to layer as we are using a controller and facade in the presentation layer that accesses the business and data layer located in web services [via a proxy], so the list of drugs must be serialized and returned to the controller for processing [display, navigation, etc].   Unfortunately, this strategy wouldn't pass our code review standards if I returned the List<T>
0
 
LVL 6

Expert Comment

by:cottsak
Comment Utility
escheider,

sorry man. i'm not full-bottle enuf on using all those patterns togetha to suggest a solution that will comply with ur strict coding standards. perhaps your architect should suggest the solution.. thats his job right?
0
 
LVL 11

Assisted Solution

by:William
William earned 250 total points
Comment Utility
The MSDN article:
The first reason is that List<T> is designed for speed and for use as an internal implementation detail, whereas Collection<T> is designed for extensibility.

I believe your architect is leaning this way for the extensibility of the Collection<T> model.
This will allow you much more flexibility in the future. Wich is always nice, although it is usually not apparent at first, maybe in 6mo or a yr or 2 when you need to go back in and 'add/mod' some code for new features ect...

It is more work up front but has way more payback later.

Just an idea if TIME is the issue...
Can you suggest an Interface for use (just for now) that has all your 'implementaion in upfront (even if it not coded yet [empty void and null returns/ throw new Not Implemented Exceptions from the class level)  ...  Just a thought

BillyDvd
0
 
LVL 4

Author Closing Comment

by:escheider
Comment Utility
Thanks for clearing things up for me ..  we have decided to implement the Collection object, as it will be beneficial for us to determine when an object is added to the collection.   Thanks for all your assistance.
0
 
LVL 6

Expert Comment

by:cottsak
Comment Utility
no sweat. it was learning for me too. ;)
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now