Home   Cover Cover Cover Cover
 

Query-Ausdruck mit Join

A08.cs
/* Quer expression with join
   This example creates a list of articles and an order consisting 
   of a list of ordered items. It then applies a join query to them 
   in order to print all ordered articles with their code, their name, 
   the ordered amount and the total price.
------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;

class Article {  // article record
  public int Code { get; set; }     // article code
  public string Name { get; set; }  // article name
  public int Price { get; set; }    // article price
}

class Item {     // order
  public int Code { get; set; }     // article code
  public int Amount { get; set; }   // ordered amount
}

public class A8 {
  
  public static void Main() {
    var articles = new List< Article > {
      new Article {Code = 101, Name = "USB-Stick 4GB", Price = 9},
      new Article {Code = 102, Name = "USB-Stick 8GB", Price = 15},
      new Article {Code = 103, Name = "USB-Stick 16GB", Price = 20},
      new Article {Code = 111, Name = "Harddisk 200GB", Price = 55},
      new Article {Code = 112, Name = "Harddisk 500GB", Price = 120},
      new Article {Code = 121, Name = "WLAN-Router 150N", Price = 39},
      new Article {Code = 122, Name = "WLAN-Router 54G", Price = 45},
      new Article {Code = 123, Name = "ADSL-Modem 108MBPS", Price = 115},
      new Article {Code = 123, Name = "ADSL-Modem 54MBPS", Price = 85}
    };
    var order = new List< Item > {
      new Item {Code = 111, Amount = 2},
      new Item {Code = 121, Amount = 1},
      new Item {Code = 101, Amount = 3}
    };
    
    var result =
      from item in order
      join article in articles on item.Code equals article.Code
      orderby item.Code
      select new {article.Code, article.Name, item.Amount, Price = article.Price * item.Amount};
    
    int total = 0;
    foreach (var x in result) {
      Console.WriteLine("{0,3} {1,-20} {2,3} {3,5}", x.Code, x.Name, x.Amount, x.Price);
      total += x.Price;
    }
    Console.WriteLine("Total:                       {0,5}", total);
  }
}