orderby

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace randomString
{
    public class Program
    {
        static Random r = new Random();
        public static void Main(string[] args)
        {
            List<string> strs = new List<string>();

            do
            {
                strs.Add(GererateString(10));
            } while (strs.Count < 10);

            Console.WriteLine("隨機字串內容如下:");
            foreach (var _str in strs)
            {
                Console.WriteLine(_str);
            }
			
			Console.WriteLine();
            Console.WriteLine("排序後的內容如下:");
			strs = (from str in strs
				    orderby str.FirstOrDefault()
				    select str).ToList();
				
            foreach (var _str in strs)
            {
                Console.WriteLine(_str);
            }
        }

        //取出最長為 maxLength 的字串
        public static string GererateString(int maxLength)
        {
            // 用來產生亂數字串用的來源,如果需要加上亂數符號可以加進來
            string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            int length = getRandomInt(maxLength, maxLength + 1);
            string str = "";

            int nth = -1;
            for (int i = 0; i < length; i++)
            {
                //透過亂數來組成字串,並且強迫此次亂數不會與上次重複。
                nth = getRandomInt(chars.Length, nth);
                str += chars[nth];
            }
            //如果回傳字串長度為0,就會重新再要過一次新的字串。
            return string.IsNullOrEmpty(str) ? GererateString(maxLength) : str;
        }

        //取出與 old 不同的數字,用來強迫取出與上一個不同的數字
        public static int getRandomInt(int size, int old)
        {
            int result = 0;
            do
            {
                result = r.Next(0, size);
            } while (result == old);
            return result;
        }
    }
}
;