?
Solved

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

Posted on 2011-02-12
3
Medium Priority
?
656 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

801 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