0 votes
122 views
asked in C# by

I have list which contains objects of type Field i.e. 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 i.e.

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

Thanks.

T.

1 Answer

0 votes
answered by (8.2k points)

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

Categories

...