Advertisement
Guest User

String array sorted and grouped sample

a guest
Nov 10th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace gf_20171109_01 {
  7.   class Program {
  8.  
  9.     static private Random random = new Random();
  10.  
  11.     static String[] randomStringArray(int arrayLength, int firstLetterRangeLength, int minLength, int lengthRangeLength) {
  12.       if (arrayLength < 0) throw new ArgumentOutOfRangeException("arrayLength");
  13.       if (firstLetterRangeLength < 1 || firstLetterRangeLength > 26) throw new ArgumentOutOfRangeException("firstLetterCount");
  14.       if (minLength < 0) throw new ArgumentOutOfRangeException("minLength");
  15.       if (lengthRangeLength < 0) throw new ArgumentOutOfRangeException("lengthRange");
  16.  
  17.       String[] retVal = new String[arrayLength];
  18.       for (int i=0; i < arrayLength; i++) {
  19.         StringBuilder sb = new StringBuilder(minLength + lengthRangeLength);
  20.         Char firstLetter = (Char)random.Next(65,65+firstLetterRangeLength); // 'A' to another letter
  21.         sb.Append(firstLetter);
  22.         int length=random.Next(minLength, minLength + lengthRangeLength);
  23.         for (int j=0; j<length; j++) {
  24.           Char nextLetter=(Char) random.Next(97, 97 + 26);
  25.           sb.Append(nextLetter);
  26.         };
  27.         retVal[i] = sb.ToString();
  28.       };
  29.       return retVal;
  30.     }
  31.  
  32.     static void Main(string[] args) {
  33.       String[] nameList = randomStringArray(8, 5, 3, 6);
  34.  
  35.       Console.WriteLine("Unsorted random names:");
  36.       for (int i=0; i < nameList.Length; i++) {
  37.         Console.WriteLine(nameList[i]);
  38.       };
  39.       Console.WriteLine();
  40.  
  41.       var nameListSortedAndGrouped=nameList
  42.             .OrderBy((String s) => s)
  43.             .GroupBy((String s) => s[0])
  44.         ;
  45.       Console.WriteLine("Sorted and grouped:");
  46.       foreach (var a in nameListSortedAndGrouped) {
  47.         Console.WriteLine("Names starting with " + a.Key.ToString() + ":");
  48.         foreach (var b in a) {
  49.           Console.WriteLine(b.ToString());
  50.         };
  51.       };
  52.  
  53.       Console.WriteLine(); Console.Write("Press any key to exit..."); Console.ReadKey();
  54.     }
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement