[TIL] 114 [C#] list์ •๋ ฌ

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: ,


list sort



list ์ •๋ ฌ (๋‚˜์ด์ˆœ, ๊ฐ€์ž…์ˆœ)

๊ตฌ์กฐ์ฒด(struct) OR class์‚ฌ์šฉ

class Program
{
    public struct agename 
    {
        public int age;
        public string name;
        public int index;

        public agename(int age, string name, int index) 
        {
            this.age = age;
            this.name = name;
            this.index = index;
        }
    }
    static void Main()
    {
        string input = Console.ReadLine();
        int testcase = Convert.ToInt32(input);
        List<agename> list = new List<agename>();
        int age = 0;
        for (int i = 0; i < testcase; i++)
        {
            string agename = Console.ReadLine();
            string[] agenames = agename.Split(' ');
            age = Convert.ToInt32(agenames[0]);
            list.Add(new agename(age, agenames[1],i));
        }

        list.Sort((a, b) =>
        {
            if (a.age != b.age)
                return a.age.CompareTo(b.age); // ๋‚˜์ด์ˆœ์œผ๋กœ ์ •๋ ฌ
            return a.index.CompareTo(b.index);
        });

        foreach (var agename in list)
        {
            Console.WriteLine($"{agename.age} {agename.name}");
        }

        Console.ReadLine();
    }
    
}

  • Sort() ๋ฉ”์„œ๋“œ๋Š” ๋‘ ๊ฐœ์˜ ๊ฐ์ฒด๋ฅผ ๋น„๊ตํ•˜๋Š” ๊ธฐ์ค€์„ ์ œ๊ณต
  • ๋น„๊ต ํ›„ ๊ทธ ๊ฒฐ๊ณผ์— ๋”ฐ๋ผ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.





์žก๋‹ด, ์ผ๊ธฐ?

์ด๋ ฅ์„œ ์ •๋ฆฌ, ์ž์†Œ์„œ ์ž‘์„ฑ, ๋ฉด์ ‘์ค€๋น„์ค‘, ์ฝ”ํ…Œ




๐Ÿ“”

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ