How to build group-by dynamically on a list of dictionaries

前端 未结 1 765
小蘑菇
小蘑菇 2021-01-15 16:01

I am trying to perform a groupby on an IEnumerable. The problem is that I do not know at compile-time which fields i want to groupby. I have found another post on stack that

1条回答
  •  别那么骄傲
    2021-01-15 16:35

    So I am able to get the groupby to work... (the select statement is another question). Thanks to c0d1ng for putting me on the right path. The syntax was not so trivial because I am using indexers and not properties...

    Below is my code:

        private void GetValuesGroupedBy(List> list, List groupbyNames, List summableNames)
        {
            // build the groupby string
            StringBuilder groupBySB = new StringBuilder();
            groupBySB.Append("new ( ");
            bool useComma = false;
            foreach (var name in groupbyNames)
            {
                if (useComma)
                    groupBySB.Append(", ");
                else
                    useComma = true;
    
                groupBySB.Append("it[\"");
                groupBySB.Append(name);
                groupBySB.Append("\"]");
                groupBySB.Append(" as ");
                groupBySB.Append(name);
            }
            groupBySB.Append(" )");
    
            var groupby = list.GroupBy(groupBySB.ToString(), "it");
        }
    

    0 讨论(0)
提交回复
热议问题