Студопедия Главная Случайная страница Обратная связь

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

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; просмотров: 440. Нарушение авторских прав; Мы поможем в написании вашей работы!




Кардиналистский и ординалистский подходы Кардиналистский (количественный подход) к анализу полезности основан на представлении о возможности измерения различных благ в условных единицах полезности...


Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит. Multisim оперирует с двумя категориями...


Композиция из абстрактных геометрических фигур Данная композиция состоит из линий, штриховки, абстрактных геометрических форм...


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

Тактические действия нарядов полиции по предупреждению и пресечению групповых нарушений общественного порядка и массовых беспорядков В целях предупреждения разрастания групповых нарушений общественного порядка (далееГНОП) в массовые беспорядки подразделения (наряды) полиции осуществляют следующие мероприятия...

Механизм действия гормонов а) Цитозольный механизм действия гормонов. По цитозольному механизму действуют гормоны 1 группы...

Алгоритм выполнения манипуляции Приемы наружного акушерского исследования. Приемы Леопольда – Левицкого. Цель...

ЛЕЧЕБНО-ПРОФИЛАКТИЧЕСКОЙ ПОМОЩИ НАСЕЛЕНИЮ В УСЛОВИЯХ ОМС 001. Основными путями развития поликлинической помощи взрослому населению в новых экономических условиях являются все...

МЕТОДИКА ИЗУЧЕНИЯ МОРФЕМНОГО СОСТАВА СЛОВА В НАЧАЛЬНЫХ КЛАССАХ В практике речевого общения широко известен следующий факт: как взрослые...

СИНТАКСИЧЕСКАЯ РАБОТА В СИСТЕМЕ РАЗВИТИЯ РЕЧИ УЧАЩИХСЯ В языке различаются уровни — уровень слова (лексический), уровень словосочетания и предложения (синтаксический) и уровень Словосочетание в этом смысле может рассматриваться как переходное звено от лексического уровня к синтаксическому...

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