Share via


방법: Join 절 결과의 순서 정렬(C# 프로그래밍 가이드)

업데이트: 2007년 11월

이 예제에서는 조인 연산 결과의 순서를 정렬하는 방법을 보여 줍니다. 순서 정렬 작업은 조인 이후에 수행됩니다. 조인하기 전에 하나 이상의 소스 시퀀스에 대해 orderby 절을 사용할 수도 있지만 이 방법은 사용하지 않는 것이 좋습니다. 일부 LINQ 공급자에서는 조인 이후에 이 정렬 순서를 유지하지 않기 때문입니다.

예제

이 쿼리는 그룹 조인을 만든 후 범위 내에 있는 category 요소를 기준으로 그룹을 정렬합니다. 익명 형식 이니셜라이저 안에서는 하위 쿼리가 제품 시퀀스에서 일치하는 모든 요소의 순서를 정렬합니다.

class HowToOrderJoins
{
    #region Data
    class Product
    {
        public string Name { get; set; }
        public int CategoryID { get; set; }
    }

    class Category
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

    // Specify the first data source.
    List<Category> categories = new List<Category>()
    { 
        new Category(){Name="Beverages", ID=001},
        new Category(){ Name="Condiments", ID=002},
        new Category(){ Name="Vegetables", ID=003},
        new Category() {  Name="Grains", ID=004},
        new Category() {  Name="Fruit", ID=005}            
    };

    // Specify the second data source.
    List<Product> products = new List<Product>()
   {
      new Product{Name="Cola",  CategoryID=001},
      new Product{Name="Tea",  CategoryID=001},
      new Product{Name="Mustard", CategoryID=002},
      new Product{Name="Pickles", CategoryID=002},
      new Product{Name="Carrots", CategoryID=003},
      new Product{Name="Bok Choy", CategoryID=003},
      new Product{Name="Peaches", CategoryID=005},
      new Product{Name="Melons", CategoryID=005},
    };
    #endregion
    static void Main()
    {
        HowToOrderJoins app = new HowToOrderJoins();
        app.OrderJoin1();

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();

    }

    void OrderJoin1()
    {
        var groupJoinQuery2 =
            from category in categories
            join prod in products on category.ID equals prod.CategoryID into prodGroup
            orderby category.Name
            select new
            {
                Category = category.Name,
                Products = from prod2 in prodGroup
                           orderby prod2.Name
                           select prod2
            };

        foreach (var productGroup in groupJoinQuery2)
        {
            Console.WriteLine(productGroup.Category);
            foreach (var prodItem in productGroup.Products)
            {
                Console.WriteLine("  {0,-10} {1}", prodItem.Name, prodItem.CategoryID);
            }
        }
    }
    /* Output:
        Beverages
          Cola       1
          Tea        1
        Condiments
          Mustard    2
          Pickles    2
        Fruit
          Melons     5
          Peaches    5
        Grains
        Vegetables
          Bok Choy   3
          Carrots    3
     */
}

코드 컴파일

  • .NET Framework 버전 3.5를 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 기본적으로 프로젝트에는 System.Core.dll에 대한 참조 및 System.Linq 네임스페이스에 대한 using 지시문이 있습니다.

  • 프로젝트에 코드를 복사합니다.

  • F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

  • 아무 키나 눌러 콘솔 창을 닫습니다.

참고 항목

개념

LINQ 쿼리 식(C# 프로그래밍 가이드)

조인 작업

참조

orderby 절(C# 참조)

join 절(C# 참조)