Студопедия — Task 2 – Additional Query Expressions Using Anonymous Types
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

Task 2 – Additional Query Expressions Using Anonymous Types






1. Combine the many features presented before to simplify the previous query. To simplify this query, you make use of a lambda expression and another query expression.

static void Query()

{

var results = from c in CreateCustomers()

select new

{

c.CustomerID,

c.City,

CustomerName = c.Name,

Stores = CreateStores().Where(s => s.City == c.City)

};

 

foreach (var result in results)

{

Console.WriteLine("{0}\t{1}", result.City, result.CustomerName);

foreach (var store in result.Stores)

Console.WriteLine("\t<{0}>", store.Name);

}

}

 

2. Press Ctrl+F5 to build run the application and notice the output is the same as the previous task. Then press any key to terminate the application.

3. Now use another approach. Rather than finding all stores per customer, the customers are joined with the stores using the Join expression. This creates a record for each customer store pair.

static void Query()

{

var results = from c in CreateCustomers()

join s in CreateStores() on c.City equals s.City

select new

{

CustomerName = c.Name,

StoreName = s.Name,

c.City,

};

 

foreach (var r in results)

Console.WriteLine("{0}\t{1}\t{2}",

r.City, r.CustomerName, r.StoreName);

}

4. Press Ctrl+F5 to build and run the program to see that a piece of data from each object is correctly merged and printed. Press any key to terminate the application.

5. Next, instead of writing each pair to the screen, create a query that counts the number of stores located in the same city as each customer and writes to the screen the customer’s name along with the number of stores located in the same city as the customer. This can be done by using a group by expression.

 

static void Query()

{

var results = from c in CreateCustomers()

join s in CreateStores() on c.City equals s.City

group s by c.Name into g

select new { CustomerName = g.Key, Count = g.Count() };

 

foreach (var r in results)

Console.WriteLine("{0}\t{1}", r.CustomerName, r.Count);

}

The group clause creates an IGrouping<string, Store> where the string is the Customer Name. Press Ctrl+F5 to build and run the code to see how many stores are located in the same city as each customer. Now press any key to terminate the application.

6. You can continue working with the previous query and order the customers by the number of stores returned in the previous queries. This can be done using the Order By expression. Also the let expression is introduced to store the result of the Count method call so that it does not have to be called twice.

static void Query()

{

var results = from c in CreateCustomers()

join s in CreateStores() on c.City equals s.City

group s by c.Name into g

let count = g.Count()

orderby count ascending

select new { CustomerName = g.Key, Count = count };

 

foreach (var r in results)

Console.WriteLine("{0}\t{1}", r.CustomerName, r.Count);

}

 

7. Press Ctrl+F5 to build and run the code to see the sorted output. Then press any key to terminate the application.

Here the orderby expression has selected the g.Count() property and returns an IEnumerable<Store>. The direction can either be set to descending or ascending. The let expression allows a variable to be stored to be further used while in scope in the query.







Дата добавления: 2015-09-07; просмотров: 417. Нарушение авторских прав; Мы поможем в написании вашей работы!



Важнейшие способы обработки и анализа рядов динамики Не во всех случаях эмпирические данные рядов динамики позволяют определить тенденцию изменения явления во времени...

ТЕОРЕТИЧЕСКАЯ МЕХАНИКА Статика является частью теоретической механики, изучающей условия, при ко­торых тело находится под действием заданной системы сил...

Теория усилителей. Схема Основная масса современных аналоговых и аналого-цифровых электронных устройств выполняется на специализированных микросхемах...

Логические цифровые микросхемы Более сложные элементы цифровой схемотехники (триггеры, мультиплексоры, декодеры и т.д.) не имеют...

Кран машиниста усл. № 394 – назначение и устройство Кран машиниста условный номер 394 предназначен для управления тормозами поезда...

Приложение Г: Особенности заполнение справки формы ву-45   После выполнения полного опробования тормозов, а так же после сокращенного, если предварительно на станции было произведено полное опробование тормозов состава от стационарной установки с автоматической регистрацией параметров или без...

Измерение следующих дефектов: ползун, выщербина, неравномерный прокат, равномерный прокат, кольцевая выработка, откол обода колеса, тонкий гребень, протёртость средней части оси Величину проката определяют с помощью вертикального движка 2 сухаря 3 шаблона 1 по кругу катания...

Классификация ИС по признаку структурированности задач Так как основное назначение ИС – автоматизировать информационные процессы для решения определенных задач, то одна из основных классификаций – это классификация ИС по степени структурированности задач...

Внешняя политика России 1894- 1917 гг. Внешнюю политику Николая II и первый период его царствования определяли, по меньшей мере три важных фактора...

Оценка качества Анализ документации. Имеющийся рецепт, паспорт письменного контроля и номер лекарственной формы соответствуют друг другу. Ингредиенты совместимы, расчеты сделаны верно, паспорт письменного контроля выписан верно. Правильность упаковки и оформления....

Studopedia.info - Студопедия - 2014-2024 год . (0.014 сек.) русская версия | украинская версия