简体   繁体   English

将Linq查询结果分组为字符串

[英]Group Linq Query Results in a String

Here is what I am trying to accomplish: 这是我要完成的工作:

I have a list of companies that offer different services. 我列出了提供不同服务的公司。 I am trying to group the services together of a company in a string format so when I can export to excel it shows up in one column. 我正在尝试以字符串格式将一家公司的服务分组在一起,因此当我可以导出到excel时,它会显示在一个列中。

Right now if a company has 4 services, they will show up 4 different times in query. 现在,如果一家公司有4个服务,它们将在查询中出现4个不同的时间。 Which is logical, just want to group them together. 这是合乎逻辑的,只想将它们分组在一起。

Here is what I have tried and get "A lambda expression with a statement body cannot be converted to an expression tree" 这是我尝试过的结果,但“带有语句主体的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 shows the error on the line, right after StringBuilder() , " Aggregate(new StringBuilder(), (a, b) " LinqPad在StringBuilder() ,“ Aggregate(new StringBuilder(), (a, b) ”之后StringBuilder()的行上显示错误。

I can get them to group in a link and when clicked, that link lists them in a format like { myservice = 1} - This is why I am using .Append 我可以将它们分组到一个链接中,然后单击该链接以{myservice = 1}之类的格式列出它们-这就是为什么我使用.Append

use below code then change your logic accordingly, hopefully this will work 使用下面的代码,然后相应地更改您的逻辑,希望这会起作用

Correction in cg.Key.ToString().Trim() cg.Key.ToString()。Trim()中的更正

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

I don't know your requirement, we can correct this if you can provide exact expected result 我不知道您的要求,如果您可以提供确切的预期结果,我们可以纠正此问题

Well as the error says you cannot convert a lambda expression with a statement body to an expression tree. 正如错误所言,您无法将具有语句主体的lambda表达式转换为表达式树。 Entity framework uses expression trees to convert to sql statements. 实体框架使用表达式树转换为sql语句。 However, you can materialize the results first with ( AsEnumerable ) and then use your code with linq to objects. 但是,您可以首先使用( 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();

Important : The aggregation will take place after all the rows were retrieved from the DB. 重要提示 :聚合将从数据库检索到所有行之后进行。

Assuming your result set can be represented in the form of the following class 假设您的结果集可以用以下类的形式表示

public class Category
{
     public string Name{get;set;}
     public string Product{get;set;}
}

You could write the following LINQ query to get the result in the way you wished to: 您可以编写以下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))
     });

Thus the result set would be in the form of: 因此,结果集将采用以下形式:

  1. Category A -> decks, scissor 类别A->甲板,剪刀
  2. Category B-> cards,crates 类别B->卡,刮板
  3. Category C-> paper, rocks 类别C->纸张,岩石

Do mark as answer if this helps. 如果有帮助,请标记为答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM