Reputation: 1738
I'm trying to use linq where it makes my code readable - foreach loops generally being easy targets.
Yet there's one that seems simple but yet the linq form escapes me:
const byte EscapeByte = 0x5C;
List<byte> result = new List<byte>();
foreach (var v in values)
{
if (v.Escaped)
{
result.Add(EscapeByte);
}
result.Add(v.DataByte);
}
return result.ToArray();
Which probably means it's best left alone.. yet I am curious if a veteran could linq it in a readable way?
Upvotes: 2
Views: 203
Reputation: 793
Here you go - an alternative solution :)
return values.Aggregate(new List<byte>(), (agg,v) =>
{
if(v.Escaped) agg.Add(EscapedByte);
agg.Add(v.DataByte);
return agg;
}, agg => agg.ToArray());
Upvotes: 0
Reputation: 23561
While the above answers may be correct and show understanding of LINQ I would argue that none of them makes the code more readable. The functional approach is not always better.
Functional approach is best when the data is not mutated because this is how mathematical functions work. This is why LINQ can select but not insert or update. Your code inserts and probably this is why it does not look good when LINQ-ified. Of course you may find the LINQ code more readable as perception of readability varies from person to person.
Upvotes: 3
Reputation: 54734
return values.SelectMany(v => v.Escaped ? new[] { EscapeByte, v.DataByte } : new[] { v.DataByte }).ToArray();
Or:
return (from v in values
from r in v.Escaped ? new[] { EscapeByte, v.DataByte } : new[] { v.DataByte }
select r).ToArray()
Upvotes: 7
Reputation: 6427
return values.Select(v => v.Escaped ? EscapeByte : v.DataByte).ToArray();
Upvotes: 0