简体   繁体   English

在列表中追加字符串 <String> 使用LINQ包含在字典中

[英]append string in List<String> contained in a dictionary using LINQ

I have list which contains objects of type Field ie List<Field> and my field class is defined as follows: 我有一个包含Field类型对象的列表,即List<Field>并且我的字段类定义如下:

Public Class Field
{
   public string FieldName { get; set; }
   public string FieldValue { get; set; }
}

This list is then converted to a dictionary of type Dictionary<string, List<string>> 然后将此列表转换为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());

I would like to use Linq to append the string values contained in the list as a single string, so technically the dictionary defined above should be defined as Dictionary<string, string> but I need a couple of extra steps when appending. 我想使用Linq将列表中包含的字符串值作为单个字符串附加,因此从技术上讲,上面定义的Dictionary<string, string>应定义为Dictionary<string, string>但是附加时我需要几个额外的步骤。

I need to add the \\r\\n in front of each values being appended and I need to make sure that these values including the new line do not get appended if the value is empty ie 我需要在每个要附加的值之前添加\\r\\n ,并且需要确保如果该值为空,则不会附加包括新行在内的这些值,即

value += (string.IsNullOrEmpty(newval) ? string.Empty : '\r\n' + newVal);

Thanks. 谢谢。

T. T.

Maybe this is what you want: 也许这就是您想要的:

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))));

Replace grp.ToList() with the logic that takes a sequence of strings and puts it together in the way you want. grp.ToList()替换为采用一系列字符串并将其以所需方式组合在一起的逻辑。

The key methods you need are .Where to ignore items (ie the nulls), and string.Join to concatenate the strings together with a custom joiner (ie newlines). 您需要的关键方法是.Where忽略项目(即null)和string.Join以将字符串与自定义连接符(即换行符)连接在一起。

Incidentally, you should use Environment.NewLine instead of '\\r\\n' to keep your code more portable. 顺便说一句,您应该使用Environment.NewLine而不是'\\r\\n'来保持代码的可移植性。

Instead of grp.ToList() in the elements selector of ToDictionnary, aggregate everything to a single string there (only do this if you have a reasonable amount of strings in there, not a very high one as it would kill performance) // Replace this grp.ToList() 代替在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM