ForEach Over Object错误 [英] ForEach over Object error

查看:24
本文介绍了ForEach Over Object错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在方法中有一个查询,因此我可以从多个位置调用i,如下所示:

private object GetData(ProfilePropertyDefinition lProfileProperty)
{   
    return from r in gServiceContext.CreateQuery("opportunity")
           join c in gServiceContext.CreateQuery("contact") on ((EntityReference)r["new_contact"]).Id equals c["contactid"] into opp
           from o in opp.DefaultIfEmpty()
           where ((EntityReference)r["new_channelpartner"]).Id.Equals(lProfileProperty.PropertyValue) && ((OptionSetValue)r["new_leadstatus"]).Equals("100000002")
           select new
           {
               OpportunityId = !r.Contains("opportunityid") ? string.Empty : r["opportunityid"],
               CustomerId = !r.Contains("customerid") ? string.Empty : ((EntityReference)r["customerid"]).Name,
               Priority = !r.Contains("opportunityratingcode") ? string.Empty : r.FormattedValues["opportunityratingcode"],
               ContactName = !r.Contains("new_contact") ? string.Empty : ((EntityReference)r["new_contact"]).Name,
           };
}

然后在另一个方法中,我调用类似于so的查询方法,并尝试遍历它:

var exportData = GetData(lProfileProperty);
foreach (var lItem in exportData)
{
}

然后,在相同的方法中,当我尝试循环遍历结果时,在Foreach上不断收到以下错误:

Foreach语句不能对‘Object’类型的变量进行操作,因为‘Object’不包含‘GetEnumerator’的公共定义

任何会导致什么以及如何修复它的想法,我都被难住了。

编辑:

采纳了乔恩的建议,在很大程度上,它似乎奏效了。但当我调用类似GetData<lProfileProperty.PropertyValue>;的方法时,它会说无法找到lProfileProperty。但它就在那里。有什么想法吗?

编辑2:我已经准备好了Jon示例中的所有内容。但我收到了一个错误:在foreach (GridDataItem lItem in exportData)上,它显示错误67无法将类型‘DotNetNuke.modules.CPCLeadShare.View.Foo’转换为‘Telerik.Web.UI.GridDataItem’。有什么办法可以解决这个问题吗?我需要能够使用DGridDataItem才能访问"单元格"。

推荐答案

编译器告诉您问题是什么:您不能迭代静态类型为object的对象。修复GetData方法的返回类型以返回实现IEnumerable的内容。

由于您返回的是匿名类型的序列,因此只需将代码更改为

private IEnumerable GetData(ProfilePropertyDefinition lProfileProperty) 
但是,您将无法访问对象中的属性,除非通过反射。要解决这个问题,您需要创建一个新类并返回它的实例。例如:

class Foo {
    public string OpportunityId { get; set; }
    public string CustomerId { get; set; }
    public string Priority { get; set; }
    public string ContactName { get; set; }
}

然后

private IEnumerable<Foo> GetData(ProfilePropertyDefinition lProfileProperty) {
   // ...
   select new Foo
       { 
           OpportunityId = !r.Contains("opportunityid") ? string.Empty : r["opportunityid"], 
           CustomerId = !r.Contains("customerid") ? string.Empty : ((EntityReference)r["customerid"]).Name, 
           Priority = !r.Contains("opportunityratingcode") ? string.Empty : r.FormattedValues["opportunityratingcode"], 
           ContactName = !r.Contains("new_contact") ? string.Empty : ((EntityReference)r["new_contact"]).Name, 
       }; 
    // ...
}

这篇关于ForEach Over Object错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆