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



Функция спроса населения на данный товар Функция спроса населения на данный товар: Qd=7-Р. Функция предложения: Qs= -5+2Р,где...

Аальтернативная стоимость. Кривая производственных возможностей В экономике Буридании есть 100 ед. труда с производительностью 4 м ткани или 2 кг мяса...

Вычисление основной дактилоскопической формулы Вычислением основной дактоформулы обычно занимается следователь. Для этого все десять пальцев разбиваются на пять пар...

Расчетные и графические задания Равновесный объем - это объем, определяемый равенством спроса и предложения...

ТРАНСПОРТНАЯ ИММОБИЛИЗАЦИЯ   Под транспортной иммобилизацией понимают мероприятия, направленные на обеспечение покоя в поврежденном участке тела и близлежащих к нему суставах на период перевозки пострадавшего в лечебное учреждение...

Кишечный шов (Ламбера, Альберта, Шмидена, Матешука) Кишечный шов– это способ соединения кишечной стенки. В основе кишечного шва лежит принцип футлярного строения кишечной стенки...

Принципы резекции желудка по типу Бильрот 1, Бильрот 2; операция Гофмейстера-Финстерера. Гастрэктомия Резекция желудка – удаление части желудка: а) дистальная – удаляют 2/3 желудка б) проксимальная – удаляют 95% желудка. Показания...

Виды нарушений опорно-двигательного аппарата у детей В общеупотребительном значении нарушение опорно-двигательного аппарата (ОДА) идентифицируется с нарушениями двигательных функций и определенными органическими поражениями (дефектами)...

Особенности массовой коммуникации Развитие средств связи и информации привело к возникновению явления массовой коммуникации...

Тема: Изучение приспособленности организмов к среде обитания Цель:выяснить механизм образования приспособлений к среде обитания и их относительный характер, сделать вывод о том, что приспособленность – результат действия естественного отбора...

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