根据这篇文章中的所有答案,这是我能想到的最通用的解决方案。
我创建了 IDictionary.Merge() 扩展的 2 个版本:
- 合并(sourceLeft, sourceRight)
- Merge(sourceLeft, sourceRight, Func mergeExpression)
第二个是第一个的修改版本,它允许您指定一个 lambda 表达式来处理这样的重复:
Dictionary<string, object> customAttributes =
HtmlHelper
.AnonymousObjectToHtmlAttributes(htmlAttributes)
.ToDictionary(
ca => ca.Key,
ca => ca.Value
);
Dictionary<string, object> fixedAttributes =
new RouteValueDictionary(
new {
@class = "form-control"
}).ToDictionary(
fa => fa.Key,
fa => fa.Value
);
//appending the html class attributes
IDictionary<string, object> editorAttributes = fixedAttributes.Merge(customAttributes, (leftValue, rightValue) => leftValue + " " + rightValue);
(您可以关注ToDictionary() 和Merge() 部分)
这是扩展类(有 2 个版本的扩展,在右侧采用 IDictionary 的集合):
public static class IDictionaryExtension
{
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IDictionary<T, U> sourceRight)
{
IDictionary<T, U> result = new Dictionary<T,U>();
sourceLeft
.Concat(sourceRight)
.ToList()
.ForEach(kvp =>
result[kvp.Key] = kvp.Value
);
return result;
}
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IDictionary<T, U> sourceRight, Func<U, U, U> mergeExpression)
{
IDictionary<T, U> result = new Dictionary<T,U>();
//Merge expression example
//(leftValue, rightValue) => leftValue + " " + rightValue;
sourceLeft
.Concat(sourceRight)
.ToList()
.ForEach(kvp =>
result[kvp.Key] =
(!result.ContainsKey(kvp.Key))
? kvp.Value
: mergeExpression(result[kvp.Key], kvp.Value)
);
return result;
}
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IEnumerable<IDictionary<T, U>> sourcesRight)
{
IDictionary<T, U> result = new Dictionary<T, U>();
new[] { sourceLeft }
.Concat(sourcesRight)
.ToList()
.ForEach(dic =>
result = result.Merge(dic)
);
return result;
}
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> sourceLeft, IEnumerable<IDictionary<T, U>> sourcesRight, Func<U, U, U> mergeExpression)
{
IDictionary<T, U> result = new Dictionary<T, U>();
new[] { sourceLeft }
.Concat(sourcesRight)
.ToList()
.ForEach(dic =>
result = result.Merge(dic, mergeExpression)
);
return result;
}
}
mergeExpression 让您轻松处理想要合并项目的方式,例如加法、除法、乘法或任何您想要的特定过程。
请注意,我尚未测试扩展的集合版本...它们可能仍需要一些调整。
此外,扩展程序不会修改原始字典,如果需要,您必须将其重新分配。