?
Solved

How do I iterate over a generic IEnumerable<T> collection

Posted on 2011-02-12
3
Medium Priority
?
676 Views
Last Modified: 2012-05-11
I am new to generics in C# and need to iterate over an IEnumerable<T> collection.  I have the following code - for info it is deriving from an EF ObjectContext (this is not important for the purposes of the question):

 
public class GenericObjectContext : System.Data.Objects.ObjectContext
    {

        public GenericObjectContext(string connectionString, string defaultContainerName)
            : base(connectionString, defaultContainerName)
        {
        }

        public void Save()
        {
            if (ValidateBeforeSave())
            {
                SaveChanges();
            }
            else
            {
                //Throw exception
            }
        }

        public IEnumerable<T> ManagedEntities<T>() where T : class
        {
            var oses = ObjectStateManager.GetObjectStateEntries();
            return oses.Where(entry => entry.Entity is T).Select(entry => (T)entry.Entity);
        }

        public bool ValidateBeforeSave()
        {            

            bool isValid = true;

            //For each loop.
            //Check each entity in the ManagedEntities collection
            //If entity is invalid, set isValid = false


            return isValid;

        }

    }

Open in new window


The ManagedEntities method returns an IEnumerable<T> where the T in question are the entities from my model. Each of these entities has a Validate() method which returns true if it is valid and false if not.

When the Save() method is called on my GenericObjectContext class, I need to call the Validate() method which then needs to iterate through the ManagedEntities collection and check each entity is valid, preferably through a foreach loop.

How can I do this?
0
Comment
Question by:pipelineconsulting
3 Comments
 
LVL 4

Expert Comment

by:HawyLem
ID: 34878311
What about
for (IEnumerator<yourtype> iterator = your_generic_collection.GetEnumerator(); iterator.MoveNext(); )
 {
   yourtype value=iterator.Current;
   //
 }

Open in new window

?
0
 

Author Comment

by:pipelineconsulting
ID: 34878376
Not sure I follow that.  What I want is something like:

 
foreach (var customer in ManagedEntities<Customer>) {
    if(customer.IsValid == false) {
        isValid = false;
    }
}

Open in new window


but instead of ... in ManagedEntites<Customer> i need ManagedEntities<T>

I could have a foreach loop for each of the entities in my model :

 
foreach(var customer in ManagedEntities<Customer>) { ... }
foreach(var customer in ManagedEntities<Order>) { ... }
foreach(var customer in ManagedEntities<OrderLine>) { ... }
foreach(var customer in ManagedEntities<Product>){ ... }

Open in new window


but this really defeats the object.  I don't know what type of entity is being managed in ManagedEntites so it needs to be generalised.
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 1000 total points
ID: 34880146
I'm not sure I'm following your question...given an IEnumerable<T> the first snippet you posted in your comment http:#a34878376 is precisely how one would iterate over it's elements.

Unless you're saying you want a method to which you could pass any type of IEnumerable<T>, in which case that method could take a parameter of type IEnumerable and pass in the IEnumerable<T> (since IEnumerable<T> implements IEnumerable).  Then you could test the type of of the first object in the collection and pass it to an overload that takes an IEnumerable<T> of the appropriate type.

private void IterateItems(IEnumerable collection)
{
    Type t = collection.AsQueryable().ElementType;
    if (t is Car)
        IterateItems((IEnumerable<Car>)collection);
    else if (t is Dog)
        IterateItems((IEnumerable<Dog>)collection);
}

private void IterateItems(IEnumerable<Car> collection)
{
    foreach (Car item in collection)
        Console.Write(item.Make);
}

private void IterateItems(IEnumerable<Dog> collection)
{
    foreach (Dog item in collection)
        Console.Write(item.Breed);
}

Open in new window

0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses
Course of the Month15 days, 9 hours left to enroll

850 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