这是我想要完成的事情:
我有一系列提供不同服务的公司。我正在尝试以字符串格式将公司的服务组合在一起,因此当我可以导出到excel时,它会显示在一列中。
现在,如果公司有4项服务,它们将在查询中显示4个不同的时间。这是合乎逻辑的,只是想将它们组合在一起。
以下是我尝试过的内容"带有语句主体的lambda表达式无法转换为表达式树"
Services = (from cc in CharityCategories join c in Cao_Categories on cc.CategoryID equals c.CategoryID
join chy in CharityYears on cc.CharityYearID equals chy.CharityYearID
where chy.CampYearID == 5 && chy.StatusID == 1
group c by c.Category into cg
select new { Categories = cg.Key.Trim()}).Aggregate(new StringBuilder(), (a, b) =>
{
if (a.Length > 0)
a.Append(",");
a.Append(b.ToString().Split('=')[1].Replace(" }", ""));
return a;
}).ToString() ,
LinqPad在StringBuilder()
之后显示错误," Aggregate(new StringBuilder(), (a, b)
"
我可以让他们在链接中进行分组,点击后,该链接会以 {myservice = 1} 的格式列出 - 这就是我使用.Append
的原因
答案 0 :(得分:0)
使用下面的代码然后相应地更改你的逻辑,希望这将起作用
cg.Key.ToString()中的更正。修剪()
Services = (from cc in CharityCategories
join c in Cao_Categories on cc.CategoryID equals c.CategoryID
join chy in CharityYears on cc.CharityYearID equals chy.CharityYearID
where chy.CampYearID == 5 && chy.StatusID == 1
group c by c.Category into cg
select new { Categories = cg.Key.ToString().Trim() }).Aggregate(new StringBuilder(), (a, b) =>
{
if (a.Length > 0)
a.Append(",");
a.Append(b.ToString().Split('=')[1].Replace(" }", ""));
return a;
}).ToString();
我不了解您的要求,如果您能提供准确的预期结果我们可以更正
答案 1 :(得分:0)
错误说你无法将带有语句体的lambda表达式转换为表达式树。实体框架使用表达式树转换为sql语句。但是,您可以先使用(AsEnumerable
)实现结果,然后将代码与linq一起用于对象。
Services = (from cc in CharityCategories
join c in Cao_Categories on cc.CategoryID equals c.CategoryID
join chy in CharityYears on cc.CharityYearID equals chy.CharityYearID
where chy.CampYearID == 5 && chy.StatusID == 1
group c by c.Category into cg
select new { Categories = cg.Key.ToString().Trim() })
.AsEnumerable()
.Aggregate(new StringBuilder(), (a, b) =>
{
if (a.Length > 0)
a.Append(",");
a.Append(b.ToString().Split('=')[1].Replace(" }", ""));
return a;
}).ToString();
重要:在从数据库中检索到所有行之后,将进行聚合。
答案 2 :(得分:0)
假设您的结果集可以用以下类的形式表示
public class Category
{
public string Name{get;set;}
public string Product{get;set;}
}
您可以编写以下LINQ查询以获得您希望的结果:
var testList = new List <Category> {
new Category {Name = "A",Product = "decks"},
new Category {Name = "B",Product = "cards"},
new Category {Name = "C",Product = "paper"},
new Category {Name = "A",Product = "scissor"},
new Category {Name = "B",Product = "crates"},
new Category {Name = "C",Product = "rocks"}
};
var finalList = testList
.GroupBy(x => x.Name)
.Select(x => new {
Category =x.Key,
Items = String.Join(",", x.Select(y => y.Product))
});
因此,结果集将采用以下形式:
如果这有帮助,请标记为答案。