![](/img/trans.png)
[英]How to merge n List<Dictionary<string, string>> into a Dictionary using Linq
[英]append string in List<String> contained in a dictionary using LINQ
我有一个包含Field类型对象的列表,即List<Field>
并且我的字段类定义如下:
Public Class Field
{
public string FieldName { get; set; }
public string FieldValue { get; set; }
}
然后将此列表转换为Dictionary<string, List<string>>
类型的Dictionary<string, List<string>>
Dictionary<string, List<string>> myResult =
myFieldList.Select(m => m)
.Select((c, i) => new { Key = c.FieldName, value = c.FieldValue })
.GroupBy(o => o.Key, o => o.value)
.ToDictionary(grp => grp.Key, grp => grp.ToList());
我想使用Linq将列表中包含的字符串值作为单个字符串附加,因此从技术上讲,上面定义的Dictionary<string, string>
应定义为Dictionary<string, string>
但是附加时我需要几个额外的步骤。
我需要在每个要附加的值之前添加\\r\\n
,并且需要确保如果该值为空,则不会附加包括新行在内的这些值,即
value += (string.IsNullOrEmpty(newval) ? string.Empty : '\r\n' + newVal);
谢谢。
T.
也许这就是您想要的:
var myResult = myFieldList.GroupBy(o => o.FieldName, o => o.FieldValue)
.ToDictionary(grp => grp.Key, grp => string.Join("\r\n",
grp.Where(x=>!string.IsNullOrEmpty(x))));
将grp.ToList()
替换为采用一系列字符串并将其以所需方式组合在一起的逻辑。
您需要的关键方法是.Where
忽略项目(即null)和string.Join
以将字符串与自定义连接符(即换行符)连接在一起。
顺便说一句,您应该使用Environment.NewLine
而不是'\\r\\n'
来保持代码的可移植性。
代替在ToDictionnary的元素选择器中的grp.ToList(),将所有内容聚合到一个字符串中(仅在其中有合理数量的字符串的情况下执行此操作,否则不要过高,因为这会降低性能)//替换这个grp.ToList()
// With this
grp
.Where(s=>!string.IsNullOrEmtpy(s)) // drop the empty lines
.Aggregate((a,b)=>a+'\r\n'+b) // Aggregate all elements to a single string, adding your separator between each
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.