Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1728
  • Last Modified:

Working with Generics -- IList<T>

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
escheider
Asked:
escheider
  • 4
  • 2
  • 2
  • +1
2 Solutions
 
WilliamCommented:
Have you looked at:
http://blogs.msdn.com/fxcop/archive/2006/04/27/585476.aspx
?

Let me know if this helps


BillyDvd
0
 
Jaime OlivaresCommented:
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
 
cottsakCommented:
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
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
cottsakCommented:
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
 
escheiderAuthor Commented:
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
 
cottsakCommented:
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
 
WilliamCommented:
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
 
escheiderAuthor Commented:
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
 
cottsakCommented:
no sweat. it was learning for me too. ;)
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now