【问题标题】:How to iterate through ICollection and append additional field如何遍历 ICollection 并附加附加字段
【发布时间】:2017-07-28 10:04:12
【问题描述】:

我有一个网格/集合对象(我们称之为 SELECT_RESULTS),它是 IList、ICollection、IEnumberable 的子对象。

SELECT_RESULTS 填充有 PL/SQL SELECT 存储过程的返回结果。

我有两个问题: 1) 我无法在我的 foreach 循环中访问 SELECT_RESULTS 的字段,并且 2) 我需要根据 SELECT_RESULTS 集合的主键值将另一个从 LINQ SELECT 派生的字段值添加到此集合中。

这是我迄今为止尝试过的:

// 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
   ???
}

【问题讨论】:

    标签: c# asp.net entity-framework linq collections


    【解决方案1】:

    很遗憾,我不知道 CollectionOfPeople 是什么。所以可能还有其他选择,比如使用接口和 DTO。

    要回答您的第一个问题,您需要将 item 转换为已知类型。如果您知道类型,则可以尝试将其强制转换为该类型。

    // 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);
    }
    

    否则你可以看看动态对象的可能性。

    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);
    }
    

    至于问题 2,您为什么不使用 DTO 来存储您的信息?如果你有 People 类,那么你可以在那里添加 CUST_NAME。使事情变得容易得多。匿名类型可能很有用,但在这种情况下,您自己似乎并不容易。

    如果您需要扩展对象,您可以考虑使用 expando 对象。看这里:Creating a dynamic, extensible C# Expando Object

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      相关资源
      最近更新 更多