Reputation: 6458
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.
Upvotes: 0
Views: 899
Reputation: 3603
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
Upvotes: 1
Reputation: 63327
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))));
Upvotes: 2
Reputation: 18296
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 (i.e. the nulls), and string.Join
to concatenate the strings together with a custom joiner (i.e. newlines).
Incidentally, you should use Environment.NewLine
instead of '\r\n'
to keep your code more portable.
Upvotes: 1