how to convert IEnumerable to byte[] in c#
is there any option in c#. the IEnumerable may contain large data
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Rajanikant HawaldarRank #110 · 20.3K reputationPosted Jan 21, 2020, 12:50 PM EST
Kunjahamed PRank #5,790 · 286 reputationPosted Jan 21, 2020, 1:24 PM EST
IEnumerablestring> myStrings = new[] { "hello", "world"}; var myBytes = myStrings.SelectMany(s => Encoding.UTF8.GetBytes(s)).ToArray();This will use
UTF8as encoding for the bytes. You might need to use a different encoding depending on what you want to do with the bytes afterwards.Note that - as written above - this is not directly reversible because you lose the information where one
stringends and where the next one starts.If you want to, you could a
NewLine(or any other identifier that you could use afterwards to split on) after each string to keep them separate:var myBytes = myStrings.Select(s => s + Environment.NewLine) . SelectMany(s => Encoding.UTF8.GetBytes(s)).ToArray();