简体   繁体   中英

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:

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>> 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.

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

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

Thanks.

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.

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

Incidentally, you should use Environment.NewLine instead of '\\r\\n' to keep your code more portable.

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

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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