Can someone improve this C# code

Posted on

Problem

Its working but I don’t think its the best way of doing it. I also changed variable names just to let you know,

       string [] columnN = AnotherString.Split(',');  //Another String is something like this = "HEhehehehehE heeh, aSKdjhkaaksjd, asldkhja slkdlk, asdajsdlka, asdljkasd, asdkasjdasd, asdasdasdl, askdjasd"
                AnotherString = "";
                int i = 0;

            foreach (string cN in columnN)
            {
                if (!string.IsNullOrEmpty(Res.ResourceManager.GetString(cN.ToLower().Trim())))
                    AnotherEmptyString += Res.ResourceManager.GetString(cN.ToLower().Trim());
                else
                    AnotherString += cN;
                i++;

                if (i < columnN.Length)
                    AnotherString += ",";
            }

I saved all resources in lower case, also if in case cN doesn’t got any resource won’t it will give an exception.

Solution

Your code should work ok. However, I would have used a list to store the intermediate results, and then string.Join to create the result. (Also perhaps Linq to filter the data, but then someone not familiar with Linq will have trouble maintaining the code.) Something like

string[] columnN = AnotherString.Split(',');
string[] stringList = new string[columnN.Length];

for (int i = 0; i < columnN.Length; i++)
{
    string cN = columnN[i];
    string resource = Res.ResourceManager.GetString(cN.ToLower().Trim()));
    stringList[i] = resource ?? cN;
}

AnotherString = string.Join(",", stringList);

I think using LINQ makes perfect sense here:

var strings = AnotherString.Split(',')
    .Select(s => Res.ResourceManager.GetString(s.ToLower().Trim())) ?? s);
AnotherString = string.Join(",", strings);

Ok a few things:

  1. Do this once and cache the result Res.ResourceManager.GetString(cN.ToLower().Trim()), the call .ToLower() creates a new string and then the .Trim() call creates yet another so you save the creation of 2 extra strings for each cN.
  2. Use a string builder instead of concatenation – every time you do += on a string, a new string is created in memory.

That gives you something like this:

string[] columnN = AnotherString.Split(',');  //Another String is something like this = "HEhehehehehE heeh, aSKdjhkaaksjd, asldkhja slkdlk, asdajsdlka, asdljkasd, asdkasjdasd, asdasdasdl, askdjasd"

var stringBuilder = new StringBuilder();

int i = 0;

foreach (string cN in columnN)
{
    var resourceText = Res.ResourceManager.GetString(cN.ToLower().Trim());

    if (!string.IsNullOrEmpty(resourceText))
    {
        stringBuilder.Append(resourceText);
    }
    else
    {
        stringBuilder.Append(cN);
    }

    i++;

    if (i < columnN.Length)
    {
        stringBuilder.Append(",");
    }
}

AnotherString = stringBuilder.ToString()

Leave a Reply

Your email address will not be published. Required fields are marked *