如何在LINQ中动态添加Dictionary对象?

时间:2014-12-18 15:04:34

标签: c# linq

var topLevel = resultRows.GroupBy(g => g["CustomerAccountType"])
            .Select(cat => new Dictionary<string, object>
{
      {"AccountGroupName", cat.First()["CustomerAccountType"] },
      {"Actual1" , cat.Sum(s => Convert.ToDecimal(s["Actual1"])) },
      {"Actual2" , cat.Sum(s => Convert.ToDecimal(s["Actual2"])) },
      {"Actual3" , cat.Sum(s => Convert.ToDecimal(s["Actual3"])) },
      {"Actual4" , cat.Sum(s => Convert.ToDecimal(s["Actual4"])) },
      {"Actual5" , cat.Sum(s => Convert.ToDecimal(s["Actual5"])) },
      {"Actual6" , cat.Sum(s => Convert.ToDecimal(s["Actual6"])) },
      {"Actual7" , cat.Sum(s => Convert.ToDecimal(s["Actual7"])) },
      {"Actual8" , cat.Sum(s => Convert.ToDecimal(s["Actual8"])) },
      {"Actual9" , cat.Sum(s => Convert.ToDecimal(s["Actual9"])) },
      {"Actual10" , cat.Sum(s => Convert.ToDecimal(s["Actual10"])) },
      {"Actual11" , cat.Sum(s => Convert.ToDecimal(s["Actual11"])) },
      {"Actual12" , cat.Sum(s => Convert.ToDecimal(s["Actual12"])) }
 });

我想通过索引或迭代在上面的字典中动态添加&#34;实际1到10。

2 个答案:

答案 0 :(得分:3)

LINQ提供了Enumerable.ToDictionary方法来创建一个查询结果的词典,例如:

var dict=myQuery.ToDictionary(item=>item.KeyProperty,item=>item.ValueProperty);

答案 1 :(得分:0)

会是这样的:

var q1 = resultRows.GroupBy(g => g["CustomerAccountType"]);

    var toLevel = q1
        .Where(g => g.Key != "CustomerAccountType")
        .ToDictionary(g => g.Key, g => (object)g.Sum(s => Convert.ToDecimal(s[g.Key])));

        toLevel.Add("AccountGroupName", q1
        .First(g => g.Key == "CustomerAccountType").Select(f => f["CustomerAccountType"]));