多列组by和仅两列

时间:2014-06-26 08:49:24

标签: .net c#-4.0

searchList.GroupBy(s =>

    new { 
    s.ClientRef,
    s.ClientName,
    s.Option, s.WineID, s.Producer, 
    s.Brand, s.Variety, s.Format, s.Vintage,
    s.MaturityTo, s.RPS, s.TradeDate, s.Target, s.AuctionRequested,
    s.UKUpdated, s.GlobalUpdated }) 

.Select(y => new { ClientRef = y.Key.ClientRef,

y.Key.ClientName, y.Key.Option, y.Key.WineID,
y.Key.Producer, y.Key.Brand, y.Key.Variety, y.Key.Format, y.Key.Vintage, 
y.Key.MaturityTo, y.Key.RPS, y.Key.TradeDate, y.Key.Target,
y.Key.AuctionRequested, y.Key.UKUpdated, y.Key.GlobalUpdated,

TotalBottles = y.Sum(z => z.Bottles), 

TotalUnitPrice = y.Sum(z => z.Unit) }).ToList();

嗨,上面是我的实际查询外观。 但我希望按键列的那些组来自字符串[] cols而不是修复。列可以是3,4或任何最多18的数字,并且可以在整个过程中进行总结。

所以我想要 的 searchList.GroupBy(S => cols.split('&#39)) .select(new {cols.split(','),TotalUnit = s.sum(z => z.Unit),TotalBottles = s.sum(z => z.Bottles)} ).ToList();

1 个答案:

答案 0 :(得分:0)

步骤1:下载System.Linq.Dynamic包或使用nuget将其添加到您的项目中。

第2步:尝试理解代码并使用它。

               string[] finalColumnList = finalGroupByCols.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);                    
                StringBuilder sb = new StringBuilder();
                int counter = 0;
                char com = ',';
                sb.Append("new ( ");
                foreach (string colName in finalColumnList)
                {
                    string right = colName;
                    string left = colName;
                    if (left == "WineID")
                    {
                        sb.Append("Convert.ToInt32(").Append("it[\"").Append(left).Append("\"] ).ToString() as ");

                    }
                    else if (left == "Format" || left == "Vintage" || left == "Bottles" || left == "MaturityTo")
                    {
                        sb.Append("Convert.ToDouble(").Append("it[\"").Append(left).Append("\"] ) as ");

                    }
                    else
                    {
                        sb.Append("it[\"").Append(left).Append("\"] as ");
                    }

                    counter++;
                    if (counter == finalColumnList.Length)
                        com = ' ';
                    sb.Append(right).Append(com);
                }
                sb.Append(")");

                var SQLval = CommonLib.DataConverter.ListToDataTableConverter(searchList).AsEnumerable().AsQueryable().GroupBy(sb.ToString(), "it")
                         .Select("new (Sum(Convert.ToDouble(it[\"Bottles\"].ToString())) as TotalBottles, Sum(Convert.ToDouble(it[\"Unit\"].ToString())) as TotalUnit,it.key)").Cast<object>().ToList(); ;