public static Write ( object element ) : void | ||
element | object | |
return | void |
public void Linq004() { //Get a list of customers indicating which month of the year they became clients(take for the month and year of the first order) var customers = dataSource.Customers.Select(c => new { Customer = c.CompanyName, Date = c.Orders.Any() ? c.Orders.DefaultIfEmpty() .OrderBy(o => o.OrderDate) .FirstOrDefault().OrderDate : // it can be replaced with ?. but i using 2015 VS without C#6 new DateTime() }); foreach (var c in customers) { ObjectDumper.Write(c.Customer + ": " + c.Date.ToShortDateString()); } }
public void LinqA102() { var perMonth = dataSource.Customers .SelectMany(o => o.Orders.Select(y => y.OrderDate)) .GroupBy(m => m.Year) .Select(s => new { s.Key, ordersCount = s.Count() }) .OrderBy(m => m.Key); ObjectDumper.Write("Year : Count of orders"); foreach (var avg in perMonth) { ObjectDumper.Write(avg.Key + " : " + avg.ordersCount); } }
public void StartingQuery_6_1() { IEnumerable <Chapter06to08.BusinessLogic.Chapter06.Unmapped.Book> books = Chapter06to08.BusinessLogic.Chapter06.Unmapped.Book.GetBooks(); IEnumerable <Chapter06to08.BusinessLogic.Chapter06.Unmapped.Subject> subjects = Chapter06to08.BusinessLogic.Chapter06.Unmapped.Subject.GetSubjects(); var query = from subject in subjects join book in books on subject.SubjectId equals book.SubjectId //where book.Price < 30 orderby subject.Description, book.Title select new { subject.Description, book.Title, book.Price }; ObjectDumper.Write(query, 1); }
public void Linq009() { var _outcome = dataSource.Customers .GroupBy(_fieldOne => _fieldOne.City) .Select(_fieldOne => new { _city = _fieldOne.Key, _intensive = _fieldOne.Average(_fieldTwo => _fieldTwo.Orders.Length), _averageSalary = _fieldOne.Average(_fieldTwo => _fieldTwo.Orders.Sum(_salary => _salary.Total)) }); foreach (var _fieldOne in _outcome) { ObjectDumper.Write(" City " + _fieldOne._city + "; Intensive " + _fieldOne._intensive + "; Salary " + _fieldOne._averageSalary); //ObjectDumper.Write(" Intensive " + _fieldOne._intensive); //ObjectDumper.Write(" Salary " + _fieldOne._averageSalary); } }
//Укажите всех клиентов, у которых указан нецифровой почтовый код или не заполнен регион или в телефоне не указан код оператора public void Linq8() { Regex regexPostalCode = new Regex(@"\D{2}"); Regex regexPhone = new Regex(@"[()]"); var customer = from c in dataSource.Customers where c.PostalCode != null where c.Region == null select c; foreach (var item in customer) { if (regexPostalCode.IsMatch(item.PostalCode) && !regexPhone.IsMatch(item.Phone)) { ObjectDumper.Write(item); } } }
public void LinqA04() { var customers = from cust in this.dataSource.Customers where cust.Orders.Any() select new { cust.CompanyName, Year = cust.Orders.ElementAt(0).OrderDate.Year, Month = cust.Orders.ElementAt(0).OrderDate.Month }; ObjectDumper.Write($"Select first order of customer"); foreach (var customer in customers) { ObjectDumper.Write(customer); } }
public void Linq14() { var clients = from c in dataSource.Customers orderby c.City group c by c.City into g select new { City = g.Key, AverageSum = g.Sum(gc => gc.Orders.Sum(o => o.Total)) / g.Sum(gc => gc.Orders.Count()), AverageIntensity = g.Sum(gc => gc.Orders.Count()) / (double)g.Count() }; foreach (var c in clients) { ObjectDumper.Write(c); } }
public void Linq8() { var products = from p in dataSource.Products let range = ( p.UnitPrice < 10 ? "cheap" : p.UnitPrice >= 10 && p.UnitPrice < 20 ? "middle" : p.UnitPrice >= 20 ? "expensive" : "unknown_category" ) orderby range select new { p.Category, p.UnitPrice, range }; foreach (var p in products) { ObjectDumper.Write(p); } }
// Ordering Operators // This sample uses orderby to sort a list of products by units in stock // from highest to lowest public void Linq33() { List <Products.Product> products = Products.GetProductList(); #region Make Sure to try yourself before looking at the code // Slightly modified used "Take(10)" to make it compare the results var sortedProducts = (from prod in products orderby prod.UnitsInStock descending select prod).Take(10); // Could apply take to "sortedProducts" // ObjectDumper.Write(sortedProducts.Take(10)); ObjectDumper.Write(sortedProducts); #endregion }
public void Linq05() { var customers = dataSource.Customers .Select(customer => new { CustomerName = customer.CompanyName, DateOfFirstOrder = customer.Orders.Select(order => (DateTime?)order.OrderDate).Min(), Turnover = customer.Orders.Sum(order => order.Total), }) .OrderBy(customer => customer.DateOfFirstOrder) .ThenByDescending(customer => customer.Turnover) .ThenBy(customer => customer.CustomerName); foreach (var customer in customers) { ObjectDumper.Write(customer); } }
public void Linq9() { var resAvg = dataSource.Customers .GroupBy(c => c.City) .Select(c => new { City = c.Key, Intensity = c.Average(p => p.Orders.Length), AverageIncome = c.Average(p => p.Orders.Sum(o => o.Total)) }); foreach (var group in resAvg) { ObjectDumper.Write($"City: {group.City}"); ObjectDumper.Write($"\tIntensity: {group.Intensity}"); ObjectDumper.Write($"\tAverage Income: {group.AverageIncome}"); } }
public void LinqTask4() { var customers = this.dataSource.Customers .Select(c => new { c.CompanyName, FirstOrder = c.Orders .Select(o => o.OrderDate) .FirstOrDefault() .ToString("MM, yyyy") }) .Where(y => y.FirstOrder != new DateTime(day: 01, month: 01, year: 01).ToString("MM, yyyy")); foreach (var c in customers) { ObjectDumper.Write(c); } }
public static void Main() { string connectionString = ConfigurationManager.ConnectionStrings["database-connection-2"].ConnectionString; using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); IEnumerable <dynamic> products = sqlConnection .Query <dynamic>("Select * from Products where Id = @Id", new { Id = 2 }); foreach (dynamic product in products) { ObjectDumper.Write(string.Format("{0}-{1}", product.Id, product.ProductName)); } } }
public void DataSetLinqLamda17() { var customers = testDS.Tables["Customers"].AsEnumerable(); var orders = testDS.Tables["Orders"].AsEnumerable(); var myOrders = customers.SelectMany(c => orders, (c, o) => new { c, o }) .Select(@t => new { @t, total = @t.o.Field <decimal>("Total") }) .Where(@t => @[email protected] <string>("CustomerID") == @[email protected] <string>("CustomerID") && @t.total >= 2000.0M) .Select(@t => new { CustomerID = @[email protected] <string>("CustomerID"), OrderID = @[email protected] <int>("OrderID"), @t.total }); ObjectDumper.Write(myOrders); }
public void Linq005() { var customers = dataSource.Customers.Where(c => c.Orders.Any()) .Select(c => new { ClientName = c.CompanyName, StartDate = c.Orders.Min(o => o.OrderDate), Total = c.Orders.Sum(o => o.Total) }).OrderByDescending(c => c.StartDate.Year) .ThenByDescending(c => c.StartDate.Month) .ThenByDescending(c => c.Total) .ThenBy(c => c.ClientName);; foreach (var c in customers) { ObjectDumper.Write(c); } }
public void Linq01() { IEnumerable <string> GetCustomersWithTotalTurnoverMoreThanX( int x, IEnumerable <Customer> customers) => customers. Where(customer => customer.Orders.Sum(o => o.Total) > x). Select(c => c.CompanyName); var productsWithTotalTurnoverMoreThan10000 = GetCustomersWithTotalTurnoverMoreThanX(10000, dataSource.Customers); var productsWithTotalTurnoverMoreThan5000 = GetCustomersWithTotalTurnoverMoreThanX(5000, dataSource.Customers); ObjectDumper.Write("Products With Annual Turnover More Than 10000:"); WriteResult(productsWithTotalTurnoverMoreThan10000); ObjectDumper.Write("Products With Annual Turnover More Than 5000:"); WriteResult(productsWithTotalTurnoverMoreThan5000); }
//список поставщиков в той же стране и том же городе public void Linq4() { var listSupplierJoin = from p in dataSource.Customers join s in dataSource.Suppliers on p.Country equals s.Country select new { CompanyName = p.CompanyName, CountryCompany = p.Country, SupplierName = s.SupplierName, CountrySupplier = s.Country }; var listSupplier = from c in dataSource.Customers from s in dataSource.Suppliers where c.Country == s.Country select new { CompanyName = c.CompanyName, CountryCompany = c.Country, SupplierName = s.SupplierName, CountrySupplier = s.Country }; foreach (var item in listSupplier) { ObjectDumper.Write(item); } }
public void LinqA08() { decimal cheapThreshold = 20; decimal expensiveThreshold = 40; var products = from prod in this.dataSource.Products group prod by( prod.UnitPrice <cheapThreshold? "Cheap" : prod.UnitPrice> expensiveThreshold? "Expensive" : "Middle price" ) into priceGroup select new { priceGroup.Key, priceGroup }; foreach (var prod in products) { ObjectDumper.Write(prod, 2); } }
public void Linq008_Sorting() { var products = dataSource.Products.Select(p => new { p.ProductID, p.ProductName, PriceCategory = p.UnitPrice <= 10 ? "Cheap" : (p.UnitPrice <= 20 ? "Medium" : "Expensive") }); foreach (var product in products) { ObjectDumper.Write(product); } }
public void DLinq41() { var categories = from p in db.Products group p by p.Category.CategoryID into g orderby g.Key select new { g.Key, MostExpensiveProducts = from p2 in g where p2.UnitPrice == g.Max(p3 => p3.UnitPrice) select p2 }; ObjectDumper.Write(categories, 1); }
public void Linq69A() { List <Products.Product> products = Products.GetProductList(); #region Linq with Lambda - Make Sure to try yourself before looking at the code var productGroups = products .GroupBy(prod => prod.Category) .Where(prodGroup => prodGroup.Any(p => p.UnitsInStock == 0)) .Select(prodGroup => new { Category = prodGroup.Key, Products = prodGroup }); Console.WriteLine(); Console.WriteLine("***********************************"); Console.Write("Linq with Lambda."); ObjectDumper.Write(productGroups.Take(1), 1); #endregion }
public void LinqTask7() { var products = this.dataSource.Products .GroupBy(p => p.Category) .Select(c => new { Category = c.Key, Stocks = c.GroupBy(s => s.UnitsInStock == 0 ? "Sold" : "In stock") .Select(e => new { Left = e.Key, Prices = e .Select(pr => new { Name = pr.ProductName, Price = pr.UnitPrice }).OrderBy(pr => pr.Price) }) }); ObjectDumper.Write(products, 2); }
public void FilteringUnmappedClrMethods_6_11a() { Console.WriteLine("This example will intentionally fail because it uses CLR methods improperly."); using (DataContext dataContext = new DataContext(ConfigurationManager.ConnectionStrings["SqlConStr"].ConnectionString)) { dataContext.Log = Console.Out; var books = dataContext.GetTable <Book>(); var query = from book in books where book.PublicationDate >= DateTime.Parse("1/1/2007") select book.PublicationDate.ToString("MM/dd/yyyy"); ObjectDumper.Write(query); } }
public void Linq004() { var customers = dataSource.Customers; var customersResult = from customer in customers where customer.Orders.Count() > 0 select new { customer.CompanyName, customer.Orders.Min(order => order.OrderDate).Month, customer.Orders.Min(order => order.OrderDate).Year }; foreach (var customer in customersResult) { ObjectDumper.Write(customer); } }
public void LinqA8() { int Cheap = 20; int Expensive = 40; var products = dataSource.Products .OrderBy(p => p.UnitPrice) .GroupBy(p => p.UnitPrice < Cheap ? "Cheap" : p.UnitPrice < Expensive ? "Average" : "Expensive") .Select(x => new { Price_Category = x.Key, Product = x.Select(y => new { y.ProductName, y.UnitPrice }) }); foreach (var category in products) { ObjectDumper.Write(category, 2); } }
public static void Main() { string connectionString = ConfigurationManager.ConnectionStrings["database-connection-2"].ConnectionString; using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var db = NorthwindDatabase.Init(sqlConnection, commandTimeout: 2); var result = db.Suppliers.All(); foreach (var supplier in result) { ObjectDumper.Write(supplier); } } }
public void Aggregates_6_14() { using (DataContext dataContext = new DataContext(ConfigurationManager.ConnectionStrings["SqlConStr"].ConnectionString)) { dataContext.Log = Console.Out; Table <Book> books = dataContext.GetTable <Book>(); var query = from book in books group book by book.SubjectId into groupedBooks select new { groupedBooks.Key, BookCount = groupedBooks.Count() }; ObjectDumper.Write(query, 1); } }
public void Linq23() { List <Customer> customers = GetCustomerList(); var waOrders = from cust in customers from order in cust.Orders where cust.Region == "WA" select new { cust.CustomerID, order.OrderID, order.OrderDate }; var allButFirst2Orders = waOrders.Skip(2); Console.WriteLine("All but first 2 orders in WA:"); foreach (var order in allButFirst2Orders) { ObjectDumper.Write(order); } }
public void Linq12() { int cheap = 25; int average = 50; var groups = from p in this.dataSource.Products group p by p.UnitPrice < cheap ? "Cheap" : p.UnitPrice < average ? "Average price" : "Expensive"; foreach (var g in groups) { ObjectDumper.Write(g.Key); foreach (var p in g) { ObjectDumper.Write(p); } } }
public void Linq001() { decimal x = 1500; var customersList = dataSource.Customers .Where(c => c.Orders.Sum(o => o.Total) > x) .Select(c => new { CustomerId = c.CustomerID, TotalSum = c.Orders.Sum(o => o.Total) }); ObjectDumper.Write($"Greater than {x}"); foreach (var customer in customersList) { ObjectDumper.Write($"CustomerId = {customer.CustomerId} TotalSum = {customer.TotalSum}\n"); } }
/// <summary> /// Writes the specified element. /// </summary> /// <param name="prefix">The prefix to print.</param> /// <param name="element">The element to dump.</param> /// <param name="depth">The iteration level.</param> /// <param name="maxcount">The maximum count of dumps.</param> /// <param name="log">The output logger.</param> public static void Write(string prefix, object element, int depth, int maxcount, TextWriter log) { ObjectDumper dumper = new ObjectDumper(depth, maxcount); dumper.writer = log; // string prefix = null; if (element != null) { dumper.Write("[" + element.GetType().Name + "]" + log.NewLine); //prefix = "[" + element.GetType().Name + "]"; } dumper.WriteObject(prefix, element); }