首页 > 解决方案 > 使用 LINQ 基于单个属性过滤 EntityCollection:

问题描述

我有一个由 fetchXML 查询组成的实体集合。

string fetch = @"
  <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
     <entity name='new_rl'>
        <attribute name='new_rlsid' />
        <attribute name='new_productid' />
        <attribute name='new_subquantity' />
        <filter type='and'>
           <condition attribute='new_sg' operator='eq' value='" + servingGroup.Value.ToString() + @"' />
           <condition attribute='new_s' operator='eq' value='' />
           <condition attribute='new_ld' operator='eq' value='" + location + @"' />
           <condition attribute='new_productid' operator='not-null' />
        </filter>
        <link-entity name='new_ys' from='new_ysid' to='new_orderid' link-type='inner' alias='ae'>
        <filter type='and'>
           <condition attribute='new_ysid' operator='eq' value='{" + yGuid.ToString() + @"}' />
        </filter>
      </link-entity>
    </entity>
  </fetch>";


EntityCollection Labels = service.RetrieveMultiple(new FetchExpression(fetch));

我需要根据“new_productid”属性过滤上述实体集合。如果两个实体的“new_productid”值相同,那么我只希望将其中一个实体呈现到新的过滤实体集合中。我需要 new_productid 和 new_subquantity 和 new_rlsid 在我的新实体集合中。

我注意到 LINQ 具有该.Distinct()属性,但是 CRM 的所有 msdn 示例都显示了如何使用早期绑定对 LINQ 执行此操作。我所有的插件都是后期绑定的,需要一个 Linq 解决方案来进行后期绑定。

标签: c#linqdynamics-crmdynamics-crm-onlinedynamics-365

解决方案


此示例显示了与 LINQ 的后期绑定:

using (var context = new OrganizationServiceContext(service))
{
    var result = (from a in context.CreateQuery("account")
                    join o in context.CreateQuery("opportunity")
                    on a.GetAttributeValue<Guid>("accountid") equals o.GetAttributeValue<Guid>("new_officeid")
                    where a.GetAttributeValue<OptionSetValue>("statecode").Value == 0
                    where o.GetAttributeValue<Guid>("parentaccountid") != Guid.Empty
                    orderby a.GetAttributeValue<string>("name")
                    select new KeyValuePair<Guid, string>(a.GetAttributeValue<Guid>("accountid"), a.GetAttributeValue<string>("name")))
                    .Distinct();
}

推荐阅读