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



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

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

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

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

Растягивание костей и хрящей. Данные способы применимы в случае закрытых зон роста. Врачи-хирурги выяснили...

ФАКТОРЫ, ВЛИЯЮЩИЕ НА ИЗНОС ДЕТАЛЕЙ, И МЕТОДЫ СНИЖЕНИИ СКОРОСТИ ИЗНАШИВАНИЯ Кроме названных причин разрушений и износов, знание которых можно использовать в системе технического обслуживания и ремонта машин для повышения их долговечности, немаловажное значение имеют знания о причинах разрушения деталей в результате старения...

Различие эмпиризма и рационализма Родоначальником эмпиризма стал английский философ Ф. Бэкон. Основной тезис эмпиризма гласит: в разуме нет ничего такого...

Факторы, влияющие на степень электролитической диссоциации Степень диссоциации зависит от природы электролита и растворителя, концентрации раствора, температуры, присутствия одноименного иона и других факторов...

Йодометрия. Характеристика метода Метод йодометрии основан на ОВ-реакциях, связанных с превращением I2 в ионы I- и обратно...

Броматометрия и бромометрия Броматометрический метод основан на окислении вос­становителей броматом калия в кислой среде...

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