Search code examples
c#asp.netentity-frameworklinqcollections

How to iterate through ICollection and append additional field


I have a grid / collection object (let's call it SELECT_RESULTS) that is a child of IList, ICollection, IEnumerable.

SELECT_RESULTS is populated with the returned results of a PL/SQL SELECT stored procedure.

I have 2 issues:

  1. I am unable to access the fields of SELECT_RESULTS in my foreach loop, and
  2. I need to add another field value derived from a LINQ SELECT onto this collection based on the Primary Key values of the SELECT_RESULTS collection.

This is what I've tried so far:

// get the list of potential CUST_NAME that will be appended 
var q = (from tableX in dbContext.CUSTOMER
         where tableX.CUST_ID = 42
         select new
           {
              tableX.CUST_ID
              tableX.CUST_NAME
      tableX.A_DATE
       } );

// trying to get results to know what type it's a collection of:
var results = SELECT_RESULTS as CollectionOfPeople;

// dilemma : item is an Object here, so I'm unable to access the   
//   different field names in the collection :-(

foreach (var item in results)
{
    // question1) how to find the matching row in the collection. 
    // I am unable to see item.ID.  
    // Only can see item.ToString, item.ToHashCode, and other Object stuff

   var q1 = q.Where (x => x.CUST_ID == item.ID);

// question 2) I need to Append the CUST_NAME into the collection
// onto the row having matching CUST_ID == ID
   ???
}

Solution

  • Unfortunately I do not know what CollectionOfPeople is. So there may be other options, like using interfaces and DTO's.

    To answer your first question, you'll need to cast item to a known type. If you know the type then you can try to cast it to that type.

    // If you know the type you could try something like this:
    foreach (People item in results)
    {
       var q1 = q.Where (x => x.CUST_ID == item.ID);
    }
    

    Otherwise you could take a look of the possibilities of dynamic objects.

    foreach (var item in results)
    {
       // This compiles but it doesn't mean it is correct.
       // A non-existing property will throw an exception.
       int i = ((dynamic)item).ID;
       var q1 = q.Where (x => x.CUST_ID == i);
    }
    

    As for question 2, why don't you use DTO's to store your information? If you have the class People, then you can add CUST_NAME there. Makes things a lot easier. Anonymous types can be useful, but in this case it seems you are making it not easy for yourself.

    If you need to expand the object you may consider using expando objects. Take a look here: Creating a dynamic, extensible C# Expando Object.