如何在
下面添加额外的词典对象var topLevel1 = resultRows.GroupBy(g => g["CustomerAccountType"])
.ToDictionary(g => g.Key, g => g.ToList());
我想在LINQ行中添加它
new Dictionary<string, object> { {"children", someDictionaryAgain}}
我想在.ToDictionary()
之后添加额外的字典对象类似
var topLevel1 = resultRows.GroupBy(g => g["CustomerAccountType"])
.ToDictionary(g => g.Key, g => g.ToList()).Add(new Dictionary<string, object> { {"somekey", "somevalueorobject"}}
这是我想要的预期输出。
var toplevel = Dictionary <stirng, object> {
{"Actual1", 0},
{"Actual2", 0}
}
之后.ToDictionary() - &gt;什么代码最好用来实现
var toplevel = Dictionary <stirng, object> {
{"Actual1", 0},
{"Actual2", 0},
{"AddedDynamically",0}
}
答案 0 :(得分:3)
ToDictionary
输出Dictionary
,因此您可以轻松地将结果保存到变量中并添加到变量中。不过,为了确保您获得string
和object
字典,您需要明确引用这些类型。
var topLevel1 = resultRows
.GroupBy(g => g["CustomerAccountType"])
.ToDictionary(
g => g.Key, // This is fine since it returns a string
g => { return g.ToList() as object; }); // Explicitlyreturn this as an object
topLevel1.Add("somekey", "somevalueorobject");
要展开嵌套馆藏,请使用SelectMany
代替Select
var topLevel1 = resultRows
.GroupBy(g => g["CustomerAccountType"])
.SelectMany(g => g.Select(v => new { Key = g.Key, Value = v })) // This creates an anonymous type for use further into the query
.ToDictionary(
g => g.Key,
g => g.Value);
答案 1 :(得分:2)
由于多种原因,你无法做到这一点。
主要是因为ToDictionary
返回一个新的字典对象(然后再分配)。在此处调用Add
将返回void
,因此您无法执行分配。
基本上,你必须单独留下第一行。要进行合并,您需要做一个foreach。以前在Merging dictionaries in C#
讨论了这部分问题基本上你最终得到一个循环:
foreach (KeyValuePair<string, object> kvp in secondDictionary)
topLevel1.Add(kvp.Key, kvp.Value);
请注意,上面的代码会在重复的密钥上中断。
答案 2 :(得分:1)
var topLevel1 = resultRows
.GroupBy(g => g["CustomerAccountType"])
.ToDictionary(
g => g.Key,
g => { return g.ToList() as object; }).Union(new Dictionary<string, object> { {"somekey", "somevalueorobject"}).ToDictionary(x=>x.Key,x=>x.Value);
答案 3 :(得分:0)
如果你使用类似的东西:
Dictionary<string,Dictionary<string,object>>
然后你有你要找的字典......
答案 4 :(得分:0)
public class Test
{
public static void test()
{
Dictionary<string, int> d1 = new Dictionary<string, int>();
Dictionary<string, int> d2 = new Dictionary<string, int>();
d1.AddRange(d2);
}
}
public static class Extensions
{
public static Dictionary<K, V> AddRange<K, V>(this Dictionary<K, V> d1, Dictionary<K, V> d2)
{
foreach (var kv in d2)
{
d1[kv.Key] = kv.Value;
}
return d1;
}
}
使用此扩展功能将: