具有多个连接结果的LINQ查询表示为逗号分隔的结果

时间:2012-05-04 08:42:47

标签: c# linq linq-to-entities

下面的查询返回一个连接到“地址”表的潜在客户列表,其中每个潜在客户可以有多个。

我希望每个潜在客户返回一个响应,地址在模型中的城市视图中连接,并用逗号分隔。如果连接结果中没有城市,则应返回“ - ”。

当前输出

Company Name | Company City
===========================
Company 1    | Glasgow
Company 1    | London
Company 2    | London
Company 3    | NULL

渴望输出

===========================
Company 1    | Glasgow, London
Company 2    | London
Company 3    | -

QUERY

 return (from t1 in db.Opportunities
                    from s1 in db.OpportunityStatus.Where(x => x.OpportunityStatus_ID == t1.StatusReason_ID)
                    from t2 in db.Leads.Where(x => x.Lead_ID == t1.Lead_ID)
                    from t3 in db.LeadAddresses.Where(x => x.Lead_ID == t2.Lead_ID).DefaultIfEmpty()
                    from t4 in db.Addresses.Where(x => x.Address_ID == t3.Address_ID).DefaultIfEmpty()
                    orderby (t1.Created) descending
                    select new FieldSalesPipelineViewModel
                    {
                        Id = t1.Opportunity_ID,
                        CompanyName = t2.Company_Name,
                        OpportunityTitle = t1.Opportunity_Title,
                        CompanyCity = "",
                        OpportunityStatusName = s1.OpportunityStatus_Name
                    }).Take(howMany);

1 个答案:

答案 0 :(得分:1)

尝试字符串连接:

CompanyCity = string.Join(",", (from p in db.Opportunities where t2.companyname == p.companyname select p.Companycity)

对于你的例子:

 return (from t1 in db.Opportunities
                    from s1 in db.OpportunityStatus.Where(x => x.OpportunityStatus_ID == t1.StatusReason_ID)
                    from t2 in db.Leads.Where(x => x.Lead_ID == t1.Lead_ID)
                    from t3 in db.LeadAddresses.Where(x => x.Lead_ID == t2.Lead_ID).DefaultIfEmpty()

                    orderby (t1.Created) descending
                    select new FieldSalesPipelineViewModel
                    {
                        Id = t1.Opportunity_ID,
                        CompanyName = t2.Company_Name,
                        OpportunityTitle = t1.Opportunity_Title,
                        CompanyCity = string.Join(",", (from t4 in db.Addresses Where t4.Address_ID == t3.Address_ID select t4.CompanyCity),
                        OpportunityStatusName = s1.OpportunityStatus_Name
                    }).Take(howMany);