[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2011-02-12
3
Medium Priority
?
669 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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

649 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