Solved

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

Posted on 2011-02-12
3
633 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 250 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

839 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