Solved

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

Posted on 2011-02-12
3
614 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

772 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

11 Experts available now in Live!

Get 1:1 Help Now