在Linq中向字典中添加新元素

时间:2015-03-27 11:54:26

标签: c# linq dictionary

我想在我的代码中添加新项目,

public PvmPivotResponse Report_GetGmrToTypeOfIPP(int ProjectPeriodId, int ResearchGroupId)
{
      PvmPivotResponse retVal = new PvmPivotResponse();

      var nodes = GetSalesHierarchyData();
      var flatNodes = nodes.FlattenTree(d => d.Id, d => d.ParentId);

      var results = flatNodes.Select(
       list => list
      .Select((d, i) => new KeyValuePair<int, FlatData>(i, d))
      .ToDictionary(pair => string.Format("level{0}", pair.Key + 1), 
                    pair => pair.Value.Text))
      .ToList();

       retVal.Data = 
            new List<object>{
                JsonConvert.SerializeObject(new { data = results },
                                            Formatting.Indented)
            };

      return retVal;
}

这是我的Json输出,但是我需要在我的字典中添加新项目,它被称为'value'

    {
      "data": [
        {
          "level1": "XXXXXX",
          "level2": "XXXXXX",
          "level3": "XXXXXX",
          "level4": "XXXXXX "
        },
       ]
    }

然后我的新输出应该是这样的,

{
      "data": [
        {
          "level1": "XXXXXX",
          "level2": "XXXXXX",
          "level3": "XXXXXX",
          "level4": "XXXXXX ",
          "val": "2"
        },
       ]
    }

那么如何在我的字典上添加这个('value')新项目?

在答案之后,我决定提供更多细节以便清楚地理解,  好吧,我有分层数据,然后获取它们我已经使用了RecursiveExtensions,请看一下[here]所以当我使用这个方法时,我从dbContext中获取了一些数据,就像这样。

public IEnumerable<FlatData> GetSalesHierarchyData()
{
    IEnumerable<FlatData> _salesHieararchy = db.SalesHierarchy
    .Select(s =>
    new FlatData()
    {
      Id = s.Id,
      ParentId = s.ParentId ?? 0,
      Text = s.Name,
      Val = 2 //This has been added after, normally it doesn't exist before.  
      }).ToList();
      return _salesHieararchy;
}

2 个答案:

答案 0 :(得分:3)

假设我理解你想要的东西,它可能就像这样简单:

  var results1 = flatNodes.Select(
   list => list
  .Select((d, i) => new KeyValuePair<int, FlatData>(i, d))
  .ToDictionary(pair => string.Format("level{0}", pair.Key + 1), pair => pair.Value.Text));

  results1.Add("val", 2); // Add your extra value.

  var results = results1.ToList();

   retVal.Data = new List<object>{JsonConvert.SerializeObject(new { data = results }, Formatting.Indented)};

  return retVal;

我不明白,为什么你要创建一个IEnumerable KeyValuePair<int, FlatData>,将其转换为字典,然后将其转换为列表。那里似乎有一些额外的步骤。

答案 1 :(得分:1)

只需添加Add方法

即可
 var dic = flatNodes.Select(
   list => list
  .Select((d, i) => new KeyValuePair<int, FlatData>(i, d))
  .ToDictionary(pair => string.Format("level{0}", pair.Key + 1), pair => pair.Value.Text));

  dic.Add("val", "2");

  var results = dic.ToList()