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?
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()
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.
return values.Select(v => v.Escaped ? EscapeByte : v.DataByte).ToArray();
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());
精彩评论