'.net core Convert byte[] to list<string>
in my project I use ISession to store a string list in session cache like this:
var cacheData= someStringList;
var byteArrayCache = CacheHelper.convertListToByteArray(cacheData);
HttpContext.Session.Set(CacheKeys.CacheKey, byteArrayCache);
the ISession Set method needs a byte[] as parameter.
Then I execute the GET method like this:
var byteArrayResponse = HttpContext.Session.Get(CacheKeys.CacheKey);
This GET is returned as a byte[] and I need to convert back to string list but I'm not being able to achieve it.
Any Ideas?
the ConvertListToByteArray method is the following:
public static byte[] convertListToByteArray(List<string> list)
{
byte[] dataAsBytes = list.SelectMany(s =>
System.Text.Encoding.UTF8.GetBytes(s + Environment.NewLine)).ToArray();
return dataAsBytes;
}
Solution 1:[1]
To convert the byte[] into List: You will need to remove the newline from the byte[] then loop through each char then add to the new list.
List<string> list = new List<string>();
foreach(byte byt in dataAsBytes) {
if(!byt.Equals(Environment.NewLine)) {
list.Add(byt.ToString());
}
}
return list.ToList();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | w4nn48cy83r |
