I have a array need to handles values that are not null
var arr = [null,2,null,5,4];
var _arr = RemoveNull(arr); // [2,5,4]
var _arr2 = Encrypt(_arr); // [e1,e2,e3]
var arr2 = Tansform(_arr2); //[null,e1,null,e2,e3]
What should I do to get arr2 from arr?
CodePudding user response:
In Encrypt method, you can ignore null. What exactly is the array data type?
public static void Main()
{
int?[] Arr = new int?[] { null,2,null,5,4 };
string[] OutArr = SkipNullAndEncrypt(Arr);
foreach(string Item in OutArr)
{
Console.Write(Item " ");
}
//Output: null e2 null e5 e4
}
private static string[] SkipNullAndEncrypt(int?[] InArr)
{
int Len = InArr.Length;
string[] OutArr = new string[Len];
int i = 0;
foreach(int? ThisItem in InArr)
{
if(ThisItem.HasValue)
{
//Encrypt call here. I have just concatenated.
OutArr[i] = "e" ThisItem.Value.ToString();
}
else
{
OutArr[i] = "null"; // Only to make it visible in the output
}
i ;
}
return OutArr;
}
From you comment, this is how you can do it:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
string[] Arr = new string[] { null, "2", null, "5", "4" };
string[] ArrNullRemoved = RemoveNull(Arr);
DisplayArr(ArrNullRemoved); //2 5 4
string[] EncArr = EncryptArr(ArrNullRemoved);
DisplayArr(EncArr);//e2 e5 e4
string[] FinArr = TransformArr(EncArr, Arr);
DisplayArr(FinArr);//null e2 null e5 e4
}
private static string[] TransformArr(string[] EncArr, string[] OgArr)
{
string[] OutArr = new string[OgArr.Length];
int i = 0;
int E_Pointer = 0;
foreach(string Item in OgArr)
{
if(string.IsNullOrWhiteSpace(Item))
{
OutArr[i] = "null"; //Only for display
}
else
{
OutArr[i] = EncArr[E_Pointer];
E_Pointer ;
}
i ;
}
return OutArr;
}
private static string[] RemoveNull(string[] InArr)
{
return InArr.Where(a => !string.IsNullOrWhiteSpace(a)).ToArray();
}
private static void DisplayArr(string[] InArr)
{
foreach(string Item in InArr)
{
Console.Write(Item " ");
}
Console.WriteLine();
}
private static string[] EncryptArr(string[] InArr)
{
int i = 0;
foreach(string Item in InArr)
{
InArr[i] = "e" Item;
i ;
}
return InArr;
}
}
CodePudding user response:
string[] arr = new string[5] { null, "b", "c", null, "e" };
var _arr = RemoveNull(arr );
var _arr2 = Encrypt(_arr);
List<string> temp = new();
int j = 0;
for (int i = 0; i < arr .Length; i )
{
if (arr [i] == null)
temp.Add(null);
else
{
temp.Add(_arr2 [j]);
j ;
}
}
var arr2 = temp.ToArray();
Input { null, "b", "c", null, "e" } output [ null, "eb", "ec", null, "ee" ]