Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this C# function
C#
internal static SortedList<string, string> doSList(string list)
        {
            SortedList<string, string> ret = new SortedList<string, string>();

            char[] charSeparators = new char[] { '|' };
            string[] l1 = list.Split('|');
            if (l1.Count() > 0)
            {
                foreach (string ll1 in l1)
                {
                    string[] l2 = ll1.Split(';');

                    if (l2.Count() == 2)
                    {
                        {
                            //ret.Add(Convert.ChangeType(l2[0], typeof(key)), Convert.ChangeType(l2[1], typeof(value)));
                            ret.Add(l2[0], l2[1]);
                        }
                    }
                }
            }
            return ret;
        }

then I require sometime later:
C#
internal static SortedList<string, int> doSList2(string list)


What I have tried:

So I did it , but VB.net fellow was able to do

VB
Friend Shared Function doSList(Of key, value)(ByVal list As String) As SortedList(Of key, value)


but I am not able to do :
C#
internal static SortedList<TKey, TValue> doSList2(string list)

Error says TKey not found, TValue not found, then I tried with T only, then T not found.

it may be newbie question, please somebody guide me to this, any link where to learn?
Posted
Updated 16-Dec-23 0:35am
v4
Comments
[no name] 16-Dec-23 0:27am    
That's not a good candidate for "generics".
https://stackoverflow.com/questions/9808035/how-do-i-make-the-return-type-of-a-method-generic

1 solution

Assuming that the Key is always a string as the input has a comma separated value format; something along these lines should do the trick.

C#
public static SortedList<string, TValue> DoSList<TValue>(string csv) where TValue : IConvertible
  {
    SortedList<string, TValue> target = new ();
     string[] firstSplitArray = csv.Split('|');
      if (firstSplitArray.Length > 0)
       {
        foreach (string t1Instance in firstSplitArray)
         {
          string[] secondSplitArray = t1Instance.Split(';');

          if (secondSplitArray.Length == 2)
           {
            {
              var result= (TValue)Convert.ChangeType(secondSplitArray[1], typeof(TValue));
              target.Add(secondSplitArray[0], result);
            }
           }
         }
       }
     return target;
   }


It can be used like this:-

C#
string testStr = "Y;5|X;6|W;7|V;8|A;1|B;2|C;3|D;4";
 SortedList<string, int> sortedList = DoSList<int>(testStr);
 foreach (var kvp in sortedList)
 Console.WriteLine($"{kvp.Key}:{kvp.Value}");

 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900