- Notifications
You must be signed in to change notification settings - Fork11
rogerwcpt/python-linq-samples
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Port of theC# 101 LINQ Samples rewritten into modern C# syntax and then also using Python, using built in methods where possible.
Python doesn't really lend itself well to functional programming because is functional methods are really procedural. There is support for lambda expressions, but you can't chain or compose your your functional operations very well as you will see compare to C# equivalent below.
Source for both C# and Python are included in thesrc folder in this repository
- To run the respective C# projects (.csproj), open the containing folder inVisual Studio Code use the Debug command
- To run the respective Python files (.py), open the file inVisual Studio Code use theRun Python File in Terminal right click menu command (requirses the Python extension)
Operation | C# | python | Comment |
---|---|---|---|
Filter | Where | (x for x in sequence if fiter(x)) | Can also usefilter(f(x), sequence) |
Projection | Select | (f(x) for x in sequence) | Can also usemap(f(x), sequence) |
SelectMany | (f(x, y) for x in sequence1 for y in sequence2) | ||
Partitioning | Take(n) | array[:n] | |
TakeWhile(predicate) | takewhile(predicate) | from itertools import takewhile | |
Skip(n) | array[n:] | ||
SkipWhile(predicate) | dropwhile(predicate, sequence) | from itertools import dropwhile | |
Ordering | OrderBy | sequence.sort() or sorted(sequence) | |
OrderBy(lambda) | sequence.sort(key=lambda) or sorted(sequence, key=lambda) | ||
OrderByDescending | sequence.sort(reverse=True) or sorted(sequence, reverse=True) | ||
OrderByDescending(lambda) | sequence.sort(key=lambda, reverse=True) or sorted(sequence, key=lambda, reverse=True) | ||
ThenBy | sequence.sort(key=lambda (key1, key2)) or sorted(sequence, key=lambda (key1, key)) | ||
ThenByDescending | sequence.sort(key=lambda (key1, -key2)) or sorted(sequence, key=lambda (key1, -key2)) or use a 2 pass sort, starting with least significant ordered = sorted(unordered, key=lambda (key2)) ordered = sorted(ordered, key=lambda (key1)) | ||
Reverse | sequence.reverse() or reversed(sequence) | ||
Grouping | GroupBy | groupby | from itertools. import groupby Grouping works on sorted sequences Once you've iterated over the grouping, you can't access it again, its empty |
Sets | Distinct | set | or Set comprehension {x for x in sequence} |
Union | union | ||
Interect | intersection | ||
Except | difference | ||
Conversion | ToArray | list | |
ToList | list | ||
ToDictionary | {key:value for (key,value) in sequence} | or usedict in conjuction withzip | |
OfType | 'filter usingisinstance as predicate | ||
Element | First | next | |
First(lambda) | next(list) | next(filter(lambda) | |
FirstOrDefault | next(list) | next(filter(lambda), default) | |
ElementAt | list[0] | ||
Generation | Enumerable.Range | range | |
Enumerable.Repeat | [x] * n or repeat(x, n) | from itertools import repeat | |
Quantifiers | Any | any | |
All | all | ||
Aggregate | Count | len | |
Count(lamda) | sum(1, iterator) | ||
Sum | sum | ||
Min | min | ||
Max | max | ||
Avg | Custom calculation usingsum /len | ||
Sum(lambda) | sum(iterator) | ||
Min(lambda) | min(iterator) | ||
Max(lambda) | max(iterator) | ||
Avg(lambda) | Custom calculation usingsum(iterator) /len | ||
Aggregate | reduce(lambda, sequence) | from functools import reduce | |
Aggregate(seed, lamda) | reduce(lambsa,seed,sequence) | from functools import reduce | |
Miscellaneous | Concat(IEnumerable) | list1 + list2 | |
SequenceEqual(IEnumerable) | list1==list2 |
For a side-by-side comparison, the originalC# source code is displayed above the equivalentpython translation.
- TheOutput shows the console output of running thepython sample.
- Outputs ending with
...
illustrates only a partial response is displayed. - The source-code for C# and python utils used are included once under the first section they're used in.
- The C# ObjectDumper util used is downloadable from MSDN -ObjectDumper.zip
- Where I haven't been able to figure out the Python implemention, I've created an empty function like this:
deff:pass
This sample uses a filter to find all elements of an array with a value less than 5.
//c#staticvoidLinq1(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varlowNums=numbers.Where(n=>n<5);Console.WriteLine("Numbers < 5:");lowNums.ForEach(Console.WriteLine);}
#pythondeflinq1():numbers= [5,4,1,3,9,8,6,7,2,0]low_nums= (xforxinnumbersifx<5)print("Numbers < 5:")shared.printN(low_nums)
Numbers < 5:41320
This sample uses a filter to find all products that are out of stock.
//c#staticvoidLinq2(){varproducts=GetProductList();varsoldOutProducts=products.Where(p=>p.UnitsInStock==0);Console.WriteLine("Sold out products:");soldOutProducts.ForEach(x=>Console.WriteLine($"{x.ProductName} is sold out!"));}
#pythondeflinq2():products=shared.getProductList()sold_out_products= (xforxinproductsifx.UnitsInStock==0)print("Sold out products:")foriteminsold_out_products:print("%s is sold out!"%item.ProductName)
Sold out products:Chef Anton's Gumbo Mix is sold out!Alice Mutton is sold out!Th�ringer Rostbratwurst is sold out!Gorgonzola Telino is sold out!Perth Pasties is sold out!
This sample uses a filter to find all products that are in stock and cost more than 3.00 per unit.
//c#publicstaticvoidLinq3(){varproducts=GetProductList();varexpensiveInStockProducts=products.Where(p=>p.UnitsInStock>0&&p.UnitPrice>3.00M);Console.WriteLine("In-stock products that cost more than 3.00:");expensiveInStockProducts.ForEach(product=>Console.WriteLine($"{product.ProductName} is in stock and costs more than 3.00."));}
#pythondeflinq3():products=shared.getProductList()expensive_in_stock_products= (xforxinproductsifx.UnitsInStock>0andx.UnitPrice>3.0000)print("In-stock products that cost more than 3.00:")foriteminexpensive_in_stock_products:print("%s is in stock and costs more than 3.00."%item.ProductName)
In-stock products that cost more than 3.00:Chai is in stock and costs more than 3.00.Chang is in stock and costs more than 3.00.Aniseed Syrup is in stock and costs more than 3.00....
This sample uses a filter to find all customers in Washington and then it uses a foreach loop to iterate over the orders collection that belongs to each customer.
//c#staticvoidLinq4(){varcustomers=GetCustomerList();Console.WriteLine("Customers from Washington and their orders:");varwaCustomers=customers.Where(c=>c.Region=="WA");waCustomers.ForEach((customer)=>{Console.WriteLine($"Customer{customer.CustomerID}:{customer.CompanyName}");customer.Orders.ForEach((order)=>{Console.WriteLine($" Order{order.OrderID}:{order.OrderDate}");});});}
#pythondeflinq4():customers=shared.getCustomerList()wa_customers= (xforxincustomersifx.Region=="WA")print("Customers from Washington and their orders:")forcustomerinwa_customers:print("Customer %s : %s"% (customer.CustomerID,customer.CompanyName))fororderincustomer.Orders:print(" Order %s: %s"% (order.OrderID,order.OrderDate))
Customers from Washington and their orders:Customer LAZYK: Lazy K Kountry Store Order 10482: 1997-03-21T00:00:00 Order 10545: 1997-05-22T00:00:00Customer TRAIH: Trail's Head Gourmet Provisioners Order 10574: 1997-06-19T00:00:00 Order 10577: 1997-06-23T00:00:00 Order 10822: 1998-01-08T00:00:00...
This sample demonstrates an indexed filter that returns digits whose name is shorter than their value.
//c#staticvoidLinq5(){vardigits=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};varshortDigits=digits.Where((digit,index)=>digit.Length<index);Console.WriteLine("Short digits:");shortDigits.ForEach(d=>Console.WriteLine($"The word{d} is shorter than its value."));}
#pythondeflinq5():digits= ["zero","one","two","three","four","five","six","seven","eight","nine"]index=0# Lambdas cant have multiple lines, so create a filter functiondeffilter_func(digit):nonlocalindexresult=len(digit)<indexindex+=1returnresultshort_digits=filter(filter_func,digits)print("Short digits:")fordinshort_digits:print("The word %s is shorter than its value."%d)
Short digits:The word five is shorter than its value.The word six is shorter than its value.The word seven is shorter than its value.The word eight is shorter than its value.The word nine is shorter than its value.
This sample projects a sequence of ints 1+ higher than those in an existing array of ints.
//c#staticvoidLinq6(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varnumsPlusOne=numbers.Select(n=>n+1);Console.WriteLine("Numbers + 1:");numsPlusOne.ForEach(Console.WriteLine);}
#pythondeflinq6():numbers= [5,4,1,3,9,8,6,7,2,0]nums_plus_one= (n+1forninnumbers)print("Numbers + 1:")shared.printN(nums_plus_one)
Numbers + 1:65241097831
This sample projects a sequence of just the names of a list of products.
//c#staticvoidLinq7(){varproducts=GetProductList();varproductNames=products.Select(p=>p.ProductName);Console.WriteLine("Product Names:");productNames.ForEach(Console.WriteLine);}
#pythondeflinq7():products=shared.getProductList()product_names= (p.ProductNameforpinproducts)print("Product Names:")shared.printS(product_names)
Product Names:ChaiChangAniseed SyrupChef Anton's Cajun SeasoningChef Anton's Gumbo Mix...
This sample projects a sequence of strings representing the text version of a sequence of integers.
//c#staticvoidLinq8(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varstrings=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};vartextNums=numbers.Select(n=>strings[n]);Console.WriteLine("Number strings:");textNums.ForEach(Console.WriteLine);}
#pythondeflinq8():numbers= [5,4,1,3,9,8,6,7,2,0]strings= ["zero","one","two","three","four","five","six","seven","eight","nine"]text_nums= (strings[n]forninnumbers)print("Number strings:")shared.printS(text_nums)
Number strings:fivefouronethreenineeightsixseventwozero
"This sample projects a sequence of the uppercase and lowercase versions of each word in the original array.
//c#staticvoidLinq9(){varwords=new[]{"aPPLE","BlUeBeRrY","cHeRry"};varupperLowerWords=words.Select(w=>new{Upper=w.ToUpper(),Lower=w.ToLower()});upperLowerWords.ForEach(ul=>Console.WriteLine($"Uppercase:{ul.Upper}, Lowercase:{ul.Lower}"));}
#pythondeflinq9():words= ["aPPLE","BlUeBeRrY","cHeRry"]upper_lower_words= (SimpleNamespace(Upper=w.upper(),Lower=w.lower())forwinwords)forwordinupper_lower_words:print("Uppercase: %s, Lowercase: %s"% (word.Upper,word.Lower))
Uppercase: APPLE, Lowercase: appleUppercase: BLUEBERRY, Lowercase: blueberryUppercase: CHERRY, Lowercase: cherry
This sample projects a sequence containing text representations of digits and whether their length is even or odd.
//c#staticvoidLinq10(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varstrings=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};vardigitOddEvens=numbers.Select(n=>new{Digit=strings[n],Even=(n%2==0)});digitOddEvens.ForEach(d=>Console.WriteLine($"The digit{d.Digit} is{(d.Even?"even":"odd")}."));}
#pythondeflinq10():numbers= [5,4,1,3,9,8,6,7,2,0]strings= ["zero","one","two","three","four","five","six","seven","eight","nine"]digit_odd_evens= (SimpleNamespace(Digit=strings[n],Even=(n%2==0))forninnumbers)fordindigit_odd_evens:print("The digit %s is %s"% (d.Digit,'even'ifd.Evenelse'odd'))
The digit five is odd.The digit four is even.The digit one is odd.The digit three is odd.The digit nine is odd.The digit eight is even.The digit six is even.The digit seven is odd.The digit two is even.The digit zero is even.
This sample projects a sequence containing some properties of Products, including UnitPrice which is renamed to Price in the resulting type.
//c#staticvoidLinq11(){varproducts=GetProductList();varproductInfos=products.Select(p=>new{p.ProductName,p.Category,Price=p.UnitPrice});Console.WriteLine("Product Info:");productInfos.ForEach(productInfo=>Console.WriteLine($"{productInfo.ProductName} is in the category{productInfo.Category} and costs{productInfo.Price} per unit."));}
#pythondeflinq11():products=shared.getProductList()product_info= (SimpleNamespace(ProductName=p.ProductName,Category=p.Category,Price=p.UnitPrice)forpinproducts)print("Product Info:")forproductinproduct_info:print("%s is in the category %s and costs %.2f per unit."% (product.ProductName,product.Category,product.Price))
Product Info:Chai is in the category Beverages and costs 18.0 per unit.Chang is in the category Beverages and costs 19.0 per unit.Aniseed Syrup is in the category Condiments and costs 10.0 per unit....
This sample uses an indexed projection to determine if the value of integers in an array match their position in the array.
//c#staticvoidLinq12(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varnumsInPlace=numbers.Select((num,index)=>new{Num=num,InPlace=(num==index)});Console.WriteLine("Number: In-place?");numsInPlace.ForEach(n=>Console.WriteLine($"{n.Num}:{n.InPlace}"));}
#pythondeflinq12():numbers= [5,4,1,3,9,8,6,7,2,0]index=0defdigit_equals_index(digit):nonlocalindexresult=digit==indexindex+=1returnresultnums_in_place= (SimpleNamespace(Num=num,InPlace=digit_equals_index(num))fornuminnumbers)print("Number: In-place?")forninnums_in_place:print("%d: %s"% (n.Num,n.InPlace))
Number: In-place?5: False4: False1: False3: True9: False8: False6: True7: True2: False0: False
This sample first filters, then projects to make a simple query that returns the text form of each digit less than 5.
//c#staticvoidLinq13(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};vardigits=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};varlowNums=numbers.Where(n=>n<5).Select(n=>digits[n]);Console.WriteLine("Numbers < 5:");lowNums.ForEach(Console.WriteLine);}
#pythondeflinq13():numbers= [5,4,1,3,9,8,6,7,2,0]digits= ["zero","one","two","three","four","five","six","seven","eight","nine"]result= (digits[n]forninnumbersifn<5)print("Numbers < 5:")shared.printS(result)
Numbers < 5:fouronethreetwozero
This sample projects a combination of 2 source arrays, then filters all pairs of numbers from both arrays such that the number from numbersA is less than the number from numbersB.
//c#staticvoidLinq14(){varnumbersA=new[]{0,2,4,5,6,8,9};varnumbersB=new[]{1,3,5,7,8};varpairs=numbersA.SelectMany(a=>numbersB,(a,b)=>new{a,b}).Where(x=>x.a<x.b);Console.WriteLine("Pairs where a < b:");pairs.ForEach(pair=>Console.WriteLine("{0} is less than {1}",pair.a,pair.b));}
#pythondeflinq14():numbers_a= [0,2,4,5,6,8,9]numbers_b= [1,3,5,7,8]pairs= ((a,b)forainnumbers_aforbinnumbers_bif (a<b))print("Pairs where a < b:")forpinpairs:print("%d is less than %d"% (p[0],p[1]))
Pairs where a < b:0 is less than 10 is less than 30 is less than 50 is less than 70 is less than 82 is less than 32 is less than 52 is less than 72 is less than 84 is less than 54 is less than 74 is less than 85 is less than 75 is less than 86 is less than 76 is less than 8
TThis sample uses a nested projection to flatten the customer orders, then filtes the order total is less than 500.00.
//c#staticvoidLinq15(){varcustomers=GetCustomerList();varorders=customers.SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Where(x=>x.order.Total<500.00M).Select(x=>new{x.customer.CustomerID,x.order.OrderID,x.order.Total});ObjectDumper.Write(orders);}
#pythondeflinq15():customers=shared.getCustomerList()orders_less_than_500= ((customer,order)forcustomerincustomersfororderincustomer.Ordersiforder.Total<500.00)orders= (SimpleNamespace(customer_id=x[0].CustomerID,order_id=x[1].OrderID,total=x[1].Total)forxinorders_less_than_500)shared.print_namespace(orders)
{CustomerId: ALFKI, OrderId: 10702, Total: 330.0}{CustomerId: ALFKI, OrderId: 10952, Total: 471.2}{CustomerId: ANATR, OrderId: 10308, Total: 88.8}{CustomerId: ANATR, OrderId: 10625, Total: 479.75}...
This sample uses a nested projection to flatten the customer orders, the filters all orders that was made in 1998 or later.
//c#staticvoidLinq16(){varcustomers=GetCustomerList();varorders=customers.SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Where(x=>x.order.OrderDate>=newDateTime(1998,1,1)).Select(x=>new{x.customer.CustomerID,x.order.OrderID,x.order.OrderDate});ObjectDumper.Write(orders);}
#pythondeflinq16():customers=shared.getCustomerList()the_date=datetime.datetime(1998,1,1)order_greater_than_date= ((customer,order)forcustomerincustomersfororderincustomer.Ordersiforder.OrderDate>the_date)orders= (SimpleNamespace(customer_id=x[0].CustomerID,order_id=x[1].OrderID,orderDate=x[1].OrderDate)forxinorder_greater_than_date)shared.print_namespace(orders)
{CustomerId: ALFKI, OrderId: 10835, OrderDate: 1998-01-15 00:00:00.000}{CustomerId: ALFKI, OrderId: 10952, OrderDate: 1998-03-16 00:00:00.000}{CustomerId: ALFKI, OrderId: 11011, OrderDate: 1998-04-09 00:00:00.000}{CustomerId: ANATR, OrderId: 10926, OrderDate: 1998-03-04 00:00:00.000}{CustomerId: ANTON, OrderId: 10856, OrderDate: 1998-01-28 00:00:00.000}...
This sample uses a nested projection to flatten the customer orders, then filters the orders where the order total is greater than 2000.00.
//c#staticvoidLinq17(){varcustomers=GetCustomerList();varorders=customers.SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Where(x=>x.order.Total>=2000.00M).Select(x=>new{x.customer.CustomerID,x.order.OrderID,x.order.Total});ObjectDumper.Write(orders);}
#pythondeflinq17():customers=shared.getCustomerList()orders_greater_than_2000= ((customer,order)forcustomerincustomersfororderincustomer.Ordersiforder.Total>2000.00)orders= (SimpleNamespace(customer_id=x[0].CustomerID,order_id=x[1].OrderID,total=x[1].Total)forxinorders_greater_than_2000)shared.print_namespace(orders)
(customer_id='ANTON', order_id=10573, total=2082.0)(customer_id='AROUT', order_id=10558, total=2142.9)(customer_id='AROUT', order_id=10953, total=4441.25)(customer_id='BERGS', order_id=10384, total=2222.4)(customer_id='BERGS', order_id=10524, total=3192.65)...
This sample fist filters on all Customers in Washington, then uses a nested projection to flatten the customer orders, then filtering on all orders greater than the cut-off date
//c#staticvoidLinq18(){varcustomers=GetCustomerList();varorders=customers.Where(c=>c.Region=="WA").SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Where(x=>x.order.OrderDate>=cutoffDate).Select(x=>new{x.customer.CustomerID,x.customer.Region,x.order.OrderID});ObjectDumper.Write(orders);}
#pythondeflinq18():customers=shared.getCustomerList()the_date=datetime.datetime(1998,1,1)order_greater_than_date= ((customer,order)forcustomerincustomersfororderincustomer.Ordersiforder.OrderDate>the_date)orders= (SimpleNamespace(customer_id=x[0].CustomerID,order_id=x[1].OrderID,orderDate=x[1].OrderDate)forxinorder_greater_than_date)shared.print_namespace(orders)
(customer_id='ALFKI', orderDate=datetime.datetime(1998, 1, 15, 0, 0), order_id=10835)(customer_id='ALFKI', orderDate=datetime.datetime(1998, 3, 16, 0, 0), order_id=10952)(customer_id='ALFKI', orderDate=datetime.datetime(1998, 4, 9, 0, 0), order_id=11011)(customer_id='ANATR', orderDate=datetime.datetime(1998, 3, 4, 0, 0), order_id=10926)(customer_id='ANTON', orderDate=datetime.datetime(1998, 1, 28, 0, 0), order_id=10856)...
//c#publicvoidLinq19(){varcustomers=GetCustomerList();varcustomerOrders=customers.SelectMany((cust,custIndex)=>cust.Orders.Select(o=>$"Customer #{custIndex+1}) has an order with OrderID{o.OrderID}"));ObjectDumper.Write(customerOrders);}
#pythondeflinq19():customers=shared.getCustomerList()index=0defget_cust_index_func():nonlocalindexindex+=1returnindexcustomer_orders= ((cust,get_cust_index_func(),order)forcustincustomersfororderincust.Orders)fortripletincustomer_orders:print("Customer #%d has an order with OrderID %d"% (triplet[1],triplet[2].OrderID))
Customer #1 has an order with OrderID 10643Customer #1 has an order with OrderID 10692Customer #1 has an order with OrderID 10702Customer #1 has an order with OrderID 10835Customer #1 has an order with OrderID 10952Customer #1 has an order with OrderID 11011Customer #2 has an order with OrderID 10308Customer #2 has an order with OrderID 10625Customer #2 has an order with OrderID 10759Customer #2 has an order with OrderID 10926...
This sample uses a partition/slice to get only the first 3 elements of the array.
//c#staticvoidLinq20(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varfirst3Numbers=numbers.Take(3);Console.WriteLine("First 3 numbers:");first3Numbers.ForEach(Console.WriteLine);}
#pythondeflinq20():numbers= [5,4,1,3,9,8,6,7,2,0]first3_numbers=numbers[:3]print("First 3 numbers:")shared.printN(first3_numbers)
First 3 numbers:541
This sample uses a partition/slice to get the first 3 orders from customers in Washington.
//c#staticvoidLinq21(){varcustomers=GetCustomerList();varfirst3WAOrders=customers.Where(c=>c.Region=="WA").SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Select(x=>new{x.customer.CustomerID,x.order.OrderID,x.order.OrderDate}).Take(3);Console.WriteLine("First 3 orders in WA:");first3WAOrders.ForEach(ObjectDumper.Write);}
#pythondeflinq21():customers=shared.getCustomerList()order_greater_than_date= ((cust,order)forcustincustomersfororderincust.Ordersifcust.Region=="WA")orders= [SimpleNamespace(customer_id=x[0].CustomerID,order_id=x[1].OrderID,orderDate=x[1].OrderDate)forxinorder_greater_than_date]first_3_orders=orders[:3]print("First 3 orders in WA:")shared.print_namespace(first_3_orders)
First 3 orders in WA:(customer_id='LAZYK', orderDate=datetime.datetime(1997, 3, 21, 0, 0), order_id=10482)(customer_id='LAZYK', orderDate=datetime.datetime(1997, 5, 22, 0, 0), order_id=10545)(customer_id='TRAIH', orderDate=datetime.datetime(1997, 6, 19, 0, 0), order_id=10574)
This sample uses a partition to get all but the first four elements of the array.
//c#staticvoidLinq22(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varallButFirst4Numbers=numbers.Skip(4);Console.WriteLine("All but first 4 numbers:");allButFirst4Numbers.ForEach(Console.WriteLine);}
#pythondeflinq22():numbers= [5,4,1,3,9,8,6,7,2,0]all_but_first4_numbers=numbers[4:]print("All but first 4 numbers:")shared.printN(all_but_first4_numbers)
All but first 4 numbers:986720
This sample uses Take to get all but the first 2 orders from customers in Washington.
//c#staticvoidLinq23(){varcustomers=GetCustomerList();varwaOrders=customers.Where(c=>c.Region=="WA").SelectMany(customer=>customer.Orders,(customer,order)=>new{customer,order}).Select(x=>new{x.customer.CustomerID,x.order.OrderID,x.order.OrderDate});varallButFirst2Orders=waOrders.Skip(2);Console.WriteLine("All but first 2 orders in WA:");ObjectDumper.Write(allButFirst2Orders);}
#pythondeflinq23():customers=shared.getCustomerList()wa_customers=filter(lambdac:c.Region=="WA",customers)wa_customer_orders=functions.select_many(wa_customers,"Orders")customer_orders=map(lambdax:SimpleNamespace(customer_id=x.item_a.CustomerID,order_id=x.item_b.OrderID,order_date=x.item_b.OrderDate),wa_customer_orders)all_but_first2=list(customer_orders)[2:]print("All but first 2 orders in WA:")shared.print_namespace(all_but_first2)
All but first 2 orders in WA:(customer_id='TRAIH', orderDate=datetime.datetime(1997, 6, 19, 0, 0), order_id=10574)(customer_id='TRAIH', orderDate=datetime.datetime(1997, 6, 23, 0, 0), order_id=10577)(customer_id='TRAIH', orderDate=datetime.datetime(1998, 1, 8, 0, 0), order_id=10822)(customer_id='WHITC', orderDate=datetime.datetime(1996, 7, 31, 0, 0), order_id=10269)(customer_id='WHITC', orderDate=datetime.datetime(1996, 11, 1, 0, 0), order_id=10344)(customer_id='WHITC', orderDate=datetime.datetime(1997, 3, 10, 0, 0), order_id=10469)(customer_id='WHITC', orderDate=datetime.datetime(1997, 3, 24, 0, 0), order_id=10483)(customer_id='WHITC', orderDate=datetime.datetime(1997, 4, 11, 0, 0), order_id=10504)(customer_id='WHITC', orderDate=datetime.datetime(1997, 7, 11, 0, 0), order_id=10596)(customer_id='WHITC', orderDate=datetime.datetime(1997, 10, 6, 0, 0), order_id=10693)(customer_id='WHITC', orderDate=datetime.datetime(1997, 10, 8, 0, 0), order_id=10696)(customer_id='WHITC', orderDate=datetime.datetime(1997, 10, 30, 0, 0), order_id=10723)(customer_id='WHITC', orderDate=datetime.datetime(1997, 11, 13, 0, 0), order_id=10740)(customer_id='WHITC', orderDate=datetime.datetime(1998, 1, 30, 0, 0), order_id=10861)(customer_id='WHITC', orderDate=datetime.datetime(1998, 2, 24, 0, 0), order_id=10904)(customer_id='WHITC', orderDate=datetime.datetime(1998, 4, 17, 0, 0), order_id=11032)(customer_id='WHITC', orderDate=datetime.datetime(1998, 5, 1, 0, 0), order_id=11066)
This sample uses a partition to return elements starting from the beginning of the array until a number is read whose value is not less than 6.
//c#staticvoidLinq24(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varfirstNumbersLessThan6=numbers.TakeWhile(n=>n<6);Console.WriteLine("First numbers less than 6:");firstNumbersLessThan6.ForEach(Console.WriteLine);}
#pythondeflinq24():numbers= [5,4,1,3,9,8,6,7,2,0]first_numbers_less_than6=takewhile(lambdax:x<6,numbers)print("First numbers less than 6:")shared.printN(first_numbers_less_than6)
First numbers less than 6:5413
This sample uses a partition to return elements starting from the beginning of the array until a number is hit that is less than its position in the array.
//c#staticvoidLinq25(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varfirstSmallNumbers=numbers.TakeWhile((n,index)=>n>=index);Console.WriteLine("First numbers not less than their position:");firstSmallNumbers.ForEach(Console.WriteLine);}
#pythondeflinq25():numbers= [5,4,1,3,9,8,6,7,2,0]index=0defdigit_greater_equal_to_index(digit):nonlocalindexresult=digit>=indexindex+=1returnresultfirst_small_numbers=takewhile(digit_greater_equal_to_index,numbers)print("First numbers not less than their position:")shared.printN(first_small_numbers)
First numbers not less than their position:54
This sample uses a partition to get the elements of the array starting from the first element divisible by 3.
//c#staticvoidLinq26(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varallButFirst3Numbers=numbers.SkipWhile(n=>n%3!=0);Console.WriteLine("All elements starting from first element divisible by 3:");allButFirst3Numbers.ForEach(Console.WriteLine);}
#pythondeflinq26():numbers= [5,4,1,3,9,8,6,7,2,0]all_but_first3_numbers=dropwhile(lambdan:n%3!=0,numbers)print("All elements starting from first element divisible by 3:")shared.printN(all_but_first3_numbers)
All elements starting from first element divisible by 3:3986720
This sample uses a partition to get the elements of the array starting from the first element less than its position.
//c#staticvoidLinq27(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varlaterNumbers=numbers.SkipWhile((n,index)=>n>=index);Console.WriteLine("All elements starting from first element less than its position:");laterNumbers.ForEach(Console.WriteLine);}
#pythondeflinq27():numbers= [5,4,1,3,9,8,6,7,2,0]index=0defdigit_greater_equal_to_index(digit):nonlocalindexresult=digit>=indexindex+=1returnresultlater_numbers=dropwhile(digit_greater_equal_to_index,numbers)print("All elements starting from first element less than its position:")shared.printN(later_numbers)
All elements starting from first element less than its position:13986720
This sample uses ordering to sort a list of words alphabetically.
//c#staticvoidLinq28(){varwords=new[]{"cherry","apple","blueberry"};varsortedWords=words.OrderBy(w=>w);Console.WriteLine("The sorted list of words:");sortedWords.ForEach(Console.WriteLine);}
#pythondeflinq28():words= ["cherry","apple","blueberry"]sorted_words=sorted(words)print("The sorted list of words:")shared.printS(sorted_words)
The sorted list of words:appleblueberrycherry
This sample uses ordering to sort a list of words by length.
//c#staticvoidLinq29(){varwords=new[]{"cherry","apple","blueberry"};varsortedWords=words.OrderBy(w=>w.Length);Console.WriteLine("The sorted list of words (by length):");sortedWords.ForEach(Console.WriteLine);}
#pythondeflinq29():words= ["cherry","apple","blueberry"]sorted_words=sorted(words,key=lambdax:len(x))print("The sorted list of words (by length):")shared.printS(sorted_words)
The sorted list of words (by length):applecherryblueberry
This sample uses ordering to sort a list of products by name.
//c#staticvoidLinq30(){varproducts=GetProductList();varsortedProducts=products.OrderBy(p=>p.ProductName);ObjectDumper.Write(sortedProducts);}
#pythondeflinq30():products=shared.getProductList()sorted_products=sorted(products,key=lambdap:p.ProductName)shared.print_namespace(sorted_products)
{productId: 17, productName: Alice Mutton, category: Meat/Poultry, unitPrice: 39.0, unitsInStock: 0}{productId: 3, productName: Aniseed Syrup, category: Condiments, unitPrice: 10.0, unitsInStock: 13}{productId: 40, productName: Boston Crab Meat, category: Seafood, unitPrice: 18.4, unitsInStock: 123}{productId: 60, productName: Camembert Pierrot, category: Dairy Products, unitPrice: 34.0, unitsInStock: 19}{productId: 18, productName: Carnarvon Tigers, category: Seafood, unitPrice: 62.5, unitsInStock: 42}...
This sample uses case-insensitive ordering to sort the words in an array.
//c#staticvoidLinq31(){varwords=new[]{"aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"};varsortedWords=words.OrderBy(a=>a,StringComparer.CurrentCultureIgnoreCase);ObjectDumper.Write(sortedWords);}
#pythondeflinq31():words= ["aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"]sorted_words=sorted(words,key=lambdas:s.casefold())shared.printS(sorted_words)
AbAcUsaPPLEBlUeBeRrYbRaNcHcHeRryClOvEr
This sample uses reverse ordering to sort a list of doubles from highest to lowest.
//c#staticvoidLinq32(){vardoubles=new[]{1.7,2.3,1.9,4.1,2.9};varsortedDoubles=doubles.OrderByDescending(d=>d);Console.WriteLine("The doubles from highest to lowest:");sortedDoubles.ForEach(Console.WriteLine);}
#pythondeflinq32():doubles= [1.7,2.3,1.9,4.1,2.9]sorted_doubles=sorted(doubles,reverse=True)print("The doubles from highest to lowest:")shared.printN(sorted_doubles)
The doubles from highest to lowest:4.12.92.31.91.7
This sample uses reverse ordering to sort a list of products by units in stock from highest to lowest.
//c#staticvoidLinq33(){varproducts=GetProductList();varsortedProducts=products.OrderByDescending(p=>p.UnitsInStock);ObjectDumper.Write(sortedProducts);}
#pythondeflinq33():products=shared.getProductList()sorted_products=sorted(products,key=lambdap:p.UnitsInStock,reverse=True)shared.print_namespace(sorted_products)
{productId: 75, productName: Rh�nbr�u Klosterbier, category: Beverages, unitPrice: 7.75, unitsInStock: 125}{productId: 40, productName: Boston Crab Meat, category: Seafood, unitPrice: 18.4, unitsInStock: 123}{productId: 6, productName: Grandma's Boysenberry Spread, category: Condiments, unitPrice: 25.0, unitsInStock: 120}{productId: 55, productName: P�t� chinois, category: Meat/Poultry, unitPrice: 24.0, unitsInStock: 115}{productId: 61, productName: Sirop d'�rable, category: Condiments, unitPrice: 28.5, unitsInStock: 113}...
This sample uses reverse case-insensitive ordering to sort the words in an array.
//c#staticvoidLinq34(){varwords=new[]{"aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"};varsortedWords=words.OrderByDescending(a=>a,StringComparer.CurrentCultureIgnoreCase);ObjectDumper.Write(sortedWords);}
#pythondeflinq34():words= ["aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"]sorted_words=sorted(words,key=lambdas:s.casefold(),reverse=True)shared.print_namespace(sorted_words)
ClOvErcHeRrybRaNcHBlUeBeRrYaPPLEAbAcUs
This sample uses nested ordering, first by length of their name, and then alphabetically by the name itself.
//c#staticvoidLinq35(){vardigits=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};varsortedDigits=digits.OrderBy(d=>d.Length).ThenBy(d=>d);Console.WriteLine("Sorted digits:");sortedDigits.ForEach(Console.WriteLine);}
#pythondeflinq35():digits= ["zero","one","two","three","four","five","six","seven","eight","nine"]sorted_digits=sorted(digits,key=lambdadigit: (len(digit),digit))print("Sorted digits:")shared.printS(sorted_digits)
Sorted digits:onesixtwofivefourninezeroeightseventhree
This sample uses case-insensitive nested ordering, with a custom comparer to sort first by word length and then by a case-insensitive sort of the words in an array.
//c#staticvoidLinq36(){varwords=new[]{"aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"};varsortedWords=words.OrderBy(a=>a.Length).ThenBy(a=>a,StringComparer.CurrentCultureIgnoreCase);ObjectDumper.Write(sortedWords);}
#pythondeflinq36():words= ["aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"]sorted_words=sorted(words,key=lambdaword: (len(word),word.casefold()))shared.printS(sorted_words)
aPPLEAbAcUsbRaNcHcHeRryClOvErBlUeBeRrY
This sample uses nested ordering to sort a list of products, first by category, and then by unit price, from highest to lowest.
//c#publicvoidLinq37(){List<Product>products=GetProductList();varsortedProducts=products.OrderBy(p=>p.Category).ThenByDescending(p=>p.UnitPrice);ObjectDumper.Write(sortedProducts);}
#pythondeflinq37():products=shared.getProductList()# negate secondary sort because its a number for reverse ordersorted_products=sorted(products,key=lambdaproduct: (product.Category,-product.UnitPrice))shared.print_namespace(sorted_products)
{productId: 38, productName: C�te de Blaye, category: Beverages, unitPrice: 263.5, unitsInStock: 17}{productId: 43, productName: Ipoh Coffee, category: Beverages, unitPrice: 46.0, unitsInStock: 17}{productId: 2, productName: Chang, category: Beverages, unitPrice: 19.0, unitsInStock: 17}{productId: 76, productName: Lakkalik��ri, category: Beverages, unitPrice: 18.0, unitsInStock: 57}{productId: 39, productName: Chartreuse verte, category: Beverages, unitPrice: 18.0, unitsInStock: 69}{productId: 1, productName: Chai, category: Beverages, unitPrice: 18.0, unitsInStock: 39}{productId: 35, productName: Steeleye Stout, category: Beverages, unitPrice: 18.0, unitsInStock: 20}{productId: 70, productName: Outback Lager, category: Beverages, unitPrice: 15.0, unitsInStock: 15}{productId: 34, productName: Sasquatch Ale, category: Beverages, unitPrice: 14.0, unitsInStock: 111}...
This sample uses uses case-insensitive reverse nested ordering to sort first by word length and then by a case-insensitive descending sort of the words in an array.
//c#staticvoidLinq38(){varwords=new[]{"aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"};varsortedWords=words.OrderBy(a=>a.Length).ThenByDescending(a=>a,StringComparer.CurrentCultureIgnoreCase);ObjectDumper.Write(sortedWords);}
#pythondeflinq38():words= ["aPPLE","AbAcUs","bRaNcH","BlUeBeRrY","ClOvEr","cHeRry"]# two pass sort, sort by least significant firstsorted_words=sorted(words,key=lambdaword:word.casefold(),reverse=True)sorted_words=sorted(sorted_words,key=lambdaword:len(word))shared.printS(sorted_words)
aPPLEClOvErcHeRrybRaNcHAbAcUsBlUeBeRrY
This sample uses reverse ordering to create a list of all digits in the array whose second letter is 'i' that is reversed from the order in the original array.
//c#staticvoidLinq39(){vardigits=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};varreversedIDigits=digits.Where(d=>d[1]=='i').Reverse();Console.WriteLine("A backwards list of the digits with a second character of 'i':");reversedIDigits.ForEach(Console.WriteLine);}
#pythondeflinq39():digits= ["zero","one","two","three","four","five","six","seven","eight","nine"]reversed_i_digits=reversed(list(filter(lambdadigit:digit[1]=="i",digits)))print("A backwards list of the digits with a second character of 'i':")shared.printS(reversed_i_digits)
A backwards list of the digits with a second character of 'i':nineeightsixfive
This sample uses grouping to partition a list of numbers by their remainder when divided by 5.
//c#staticvoidLinq40(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varnumberGroups=numbers.GroupBy(n=>n%5).Select(x=>new{Remainder=x.Key,Numbers=x});numberGroups.ForEach((g)=>{Console.WriteLine("Numbers with a remainder of {0} when divided by 5:",g.Remainder);g.Numbers.ForEach(Console.WriteLine);});}
#pythondeflinq40():numbers= [5,4,1,3,9,8,6,7,2,0]# First create a record of numbers and their modulus of 5number_remainders=map(lambdan:SimpleNamespace(Number=n,Remainder=n%5),numbers)# Group By only works on sorted lists, so sort by both fieldssorted_by_reminder=sorted(number_remainders,key=lambdax: (x.Remainder,x.Number))remainder_groups=groupby(sorted_by_reminder,key=lambdanr:nr.Remainder)forkey,itemsinremainder_groups:print("Numbers with a remainder of %d when divided by 5:"%key)foriteminitems:print(item.Number)
Numbers with a remainder of 0 when divided by 5:50Numbers with a remainder of 1 when divided by 5:16Numbers with a remainder of 2 when divided by 5:72Numbers with a remainder of 3 when divided by 5:38Numbers with a remainder of 4 when divided by 5:49
This sample uses grouping to partition a list of words by their first letter.
//c#staticvoidLinq41(){varwords=new[]{"blueberry","chimpanzee","abacus","banana","apple","cheese"};varwordGroups=words.GroupBy(w=>w[0]).Select(g=>new{FirstLetter=g.Key,Words=g});wordGroups.ForEach((g)=>{Console.WriteLine($"Words that start with the letter '{g.FirstLetter}':");g.Words.ForEach(Console.WriteLine);});}
#pythondeflinq41():words= ["blueberry","chimpanzee","abacus","banana","apple","cheese"]first_letter_words=map(lambdaw:SimpleNamespace(Letter=w[0],Word=w),words)# Group By only works on sorted lists, so sort by both fieldssorted_letter_words=sorted(first_letter_words,key=lambdax: (x.Word,x.Letter))letter_groups=groupby(sorted_letter_words,key=lambdanr:nr.Letter)forkey,itemsinletter_groups:print("Words that start with the letter '%s':"%key)foriteminitems:print(item.Word)
Words that start with the letter 'a':abacusappleWords that start with the letter 'b':bananablueberryWords that start with the letter 'c':cheesechimpanzee
This sample uses grouping to partition a list of products by category.
//c#staticvoidLinq42(){varproducts=GetProductList();varorderGroups=products.GroupBy(p=>p.Category).Select(g=>new{Category=g.Key,Products=g});ObjectDumper.Write(orderGroups,1);}
#pythondeflinq42():products=shared.getProductList()sorted_by_category=sorted(products,key=lambdap:p.Category)order_groups=groupby(sorted_by_category,key=lambdap:p.Category)forkey,itemsinorder_groups:print("Products in the category '%s':"%key)print(list(items))
Products in the category 'Beverages':[{productId: 1, productName: Chai, category: Beverages, unitPrice: 18.00, unitsInStock: 39}, {productId: 2, productName: Products in the category 'Condiments':[{productId: 3, productName: Aniseed Syrup, category: Condiments, unitPrice: 10.00, unitsInStock: 13}, {productId: 4, Products in the category 'Confections':[{productId: 16, productName: Pavlova, category: Confections, unitPrice: 17.45, unitsInStock: 29}, {productId: 19, Products in the category 'Dairy Products':[{productId: 11, productName: Queso Cabrales, category: Dairy Products, unitPrice: 21.00, unitsInStock: 22}, {productId: Products in the category 'Grains/Cereals':[{productId: 22, productName: Gustaf's Knäckebröd, category: Grains/Cereals, unitPrice: 21.00, unitsInStock: 104}, Products in the category 'Meat/Poultry':[{productId: 9, productName: Mishi Kobe Niku, category: Meat/Poultry, unitPrice: 97.00, unitsInStock: 29}, {productId: 17,Products in the category 'Produce':[{productId: 7, productName: Uncle Bob's Organic Dried Pears, category: Produce, unitPrice: 30.00, unitsInStock: 15}, Products in the category 'Seafood':[{productId: 10, productName: Ikura, category: Seafood, unitPrice: 31.00, unitsInStock: 31}, {productId: 13, productName:
This sample uses nested grouping to partition a list of each customer's orders, first by year, and then by month.
//c#publicvoidLinq43(){varcustomers=GetCustomerList();varcustomerOrderGroups=customers.Select(c=>new{c.CompanyName,YearGroups=(c.Orders.GroupBy(y=>y.OrderDate.Year).Select(YearGroup=>new{Year=YearGroup.Key,MonthGroups=(YearGroup.GroupBy(m=>m.OrderDate.Month).Select(MonthGroup=>new{Month=MonthGroup.Key,Orders=MonthGroup}))}))});ObjectDumper.Write(customerOrderGroups,3);}
#pythondeflinq43():pass
{CompanyName: Alfreds Futterkiste, YearGroups: {{Year: 1997, MonthGroups: {{Month: 8, Orders: {{orderId: 10643, orderDate: 1997-08-25 00:00:00.000, total: 814.5}}}, {Month: 10, Orders: {{orderId: 10692, orderDate: 1997-10-03 00:00:00.000, total: 878.0}, {orderId: 10702, orderDate: 1997-10-13 00:00:00.000, total: 330.0}}}}}, {Year: 1998, MonthGroups: {{Month: 1, Orders: {{orderId: 10835, orderDate: 1998-01-15 00:00:00.000, total: 845.8}}}, {Month: 3, Orders: {{orderId: 10952, orderDate: 1998-03-16 00:00:00.000, total: 471.2}}}, {Month: 4, Orders: {{orderId: 11011, orderDate: 1998-04-09 00:00:00.000, total: 933.5}}}}}}}{CompanyName: Ana Trujillo Emparedados y helados, YearGroups: {{Year: 1996, MonthGroups: {{Month: 9, Orders: {{orderId: 10308, orderDate: 1996-09-18 00:00:00.000, total: 88.8}}}}}, {Year: 1997, MonthGroups: {{Month: 8, Orders: {{orderId: 10625, orderDate: 1997-08-08 00:00:00.000, total: 479.75}}}, {Month: 11, Orders: {{orderId: 10759, orderDate: 1997-11-28 00:00:00.000, total: 320.0}}}}}, {Year: 1998, MonthGroups: {{Month: 3, Orders: {{orderId: 10926, orderDate: 1998-03-04 00:00:00.000, total: 514.4}}}}}}}
This sample removes all duplicate elements in a sequence of factors of 300.
//c#staticvoidLinq46(){int[]factorsOf300={2,2,3,5,5};varuniqueFactors=factorsOf300.Distinct();Console.WriteLine("Prime factors of 300:");uniqueFactors.ForEach(Console.WriteLine);}
#pythondeflinq46():factors_of300= [2,2,3,5,5]unique_factors=set(factors_of300)print("Prime factors of 300:")shared.printN(unique_factors)
Prime factors of 300:235
This sample gets distint Category names from all the products.
//c#staticvoidLinq47(){varproducts=GetProductList();varcategoryNames=products.Select(p=>p.Category).Distinct();Console.WriteLine("Category names:");categoryNames.ForEach(Console.WriteLine);}
#pythondeflinq47():products=shared.getProductList()category_names= {p.Categoryforpinproducts}print("Category names:")shared.printS(category_names)
Category names:BeveragesDairy ProductsCondimentsMeat/PoultryProduceSeafoodGrains/CerealsConfections
This sample creates a Union of sequences that contains unique values from both arrays.
//c#staticvoidLinq48(){int[]numbersA={0,2,4,5,6,8,9};int[]numbersB={1,3,5,7,8};varuniqueNumbers=numbersA.Union(numbersB);Console.WriteLine("Unique numbers from both arrays:");uniqueNumbers.ForEach(Console.WriteLine);}
#pythondeflinq48():numbers_a= [0,2,4,5,6,8,9]numbers_b= [1,3,5,7,8]unique_numbers=set(numbers_a+numbers_b)print("Unique numbers from both arrays:")shared.printN(unique_numbers)
Unique numbers from both arrays:0123456789
This sample creates a Union of sequences that contains the distinct first letter from both product and customer names
//c#staticvoidLinq49(){varproducts=GetProductList();varcustomers=GetCustomerList();varproductFirstChars=products.Select(p=>p.ProductName[0]);varcustomerFirstChars=customers.Select(c=>c.CompanyName[0]);varuniqueFirstChars=productFirstChars.Union(customerFirstChars);Console.WriteLine("Unique first letters from Product names and Customer names:");uniqueFirstChars.ForEach(Console.WriteLine);}
#pythondeflinq49():products=shared.getProductList()customers=shared.getCustomerList()product_first_chars= {p.ProductName[0]forpinproducts}customer_first_chars= {c.CompanyName[0]forcincustomers}unique_first_chars=product_first_chars.union(customer_first_chars)print("Unique first letters from Product names and Customer names:")shared.printS(unique_first_chars)
Unique first letters from Product names and Customer names:GWRIPZLUCONFADTEJKSQHMBV
This sample creates Intersection that contains the common values shared by both arrays.
//c#staticvoidLinq50(){int[]numbersA={0,2,4,5,6,8,9};int[]numbersB={1,3,5,7,8};varcommonNumbers=numbersA.Intersect(numbersB);Console.WriteLine("Common numbers shared by both arrays:");commonNumbers.ForEach(Console.WriteLine);}
#pythondeflinq50():numbers_a= [0,2,4,5,6,8,9]numbers_b= [1,3,5,7,8]common_numbers=set(numbers_a).intersection((set(numbers_b)))print("Common numbers shared by both arrays:")shared.printN(common_numbers)
Common numbers shared by both arrays:85
This sample creates Intersection that contains contains the common first letter from both product and customer names.
//c#staticvoidLinq51(){varproducts=GetProductList();varcustomers=GetCustomerList();varproductFirstChars=products.Select(p=>p.ProductName[0]);varcustomerFirstChars=customers.Select(c=>c.CompanyName[0]);varcommonFirstChars=productFirstChars.Intersect(customerFirstChars);Console.WriteLine("Common first letters from Product names and Customer names:");commonFirstChars.ForEach(Console.WriteLine);}
#pythondeflinq51():products=shared.getProductList()customers=shared.getCustomerList()product_first_chars= {p.ProductName[0]forpinproducts}customer_first_chars= {c.CompanyName[0]forcincustomers}unique_first_chars=product_first_chars.intersection(customer_first_chars)print("Common first letters from Product names and Customer names:")shared.printS(unique_first_chars)
Common first letters from Product names and Customer names:ATCEQOWPFSGLVMKNIBR
This sample creates a sequence that excludes the values from the second sequence.
//c#staticvoidLinq52(){int[]numbersA={0,2,4,5,6,8,9};int[]numbersB={1,3,5,7,8};varaOnlyNumbers=numbersA.Except(numbersB);Console.WriteLine("Numbers in first array but not second array:");aOnlyNumbers.ForEach(Console.WriteLine);}
#pythondeflinq52():numbers_a= [0,2,4,5,6,8,9]numbers_b= [1,3,5,7,8]a_only_numbers=set(numbers_a).difference((set(numbers_b)))print("Numbers in first array but not second array:")shared.printN(a_only_numbers)
Numbers in first array but not second array:09246
This sample creates a sequence that the first letters of product names that but excludes letters of customer names first letter.
//c#staticvoidLinq53(){varproducts=GetProductList();varcustomers=GetCustomerList();varproductFirstChars=products.Select(p=>p.ProductName[0]);varcustomerFirstChars=customers.Select(c=>c.CompanyName[0]);varproductOnlyFirstChars=productFirstChars.Except(customerFirstChars);Console.WriteLine("First letters from Product names, but not from Customer names:");productOnlyFirstChars.ForEach(Console.WriteLine);}
#pythondeflinq53():products=shared.getProductList()customers=shared.getCustomerList()product_first_chars= {p.ProductName[0]forpinproducts}customer_first_chars= {c.CompanyName[0]forcincustomers}unique_first_chars=product_first_chars.difference(customer_first_chars)print("First letters from Product names, but not from Customer names:")shared.printS(unique_first_chars)
First letters from Product names, but not from Customer names:ZJU
This sample converts a list ti an array.
//c#staticvoidLinq54(){varlist=newList<double>{1.7,2.3,1.9,4.1,2.9};vardoublesArray=list.OrderByDescending(d=>d).ToArray();Console.WriteLine("Every other double from highest to lowest:");for(vard=0;d<doublesArray.Length;d+=2){Console.WriteLine(doublesArray[d]);}}
#pythondeflinq54():doubles= [1.7,2.3,1.9,4.1,2.9]sorted_doubles=sorted(doubles,reverse=True)doubles_array=list(sorted_doubles)print("Every other double from highest to lowest:")d=0whiled<len(doubles_array):print(doubles_array[d])d+=2
Every other double from highest to lowest:4.12.31.7
This sample converts an array to a list
//c#staticvoidLinq55(){varwords=new[]{"cherry","apple","blueberry"};varwordList=words.OrderBy(x=>x).ToList();Console.WriteLine("The sorted word list:");wordList.ForEach(Console.WriteLine);}
#pythondeflinq55():words= ["cherry","apple","blueberry"]sorted_words=sorted(words)word_list=list(sorted_words)print("The sorted word list:")shared.printN(word_list)
The sorted word list:appleblueberrycherry
This sample converts an array of records to a dictionary
//c#staticvoidLinq56(){varscoreRecords=new[]{new{Name="Alice",Score=50},new{Name="Bob",Score=40},new{Name="Cathy",Score=45}};varscoreRecordsDict=scoreRecords.ToDictionary(sr=>sr.Name);Console.WriteLine("Bob's score: {0}",scoreRecordsDict["Bob"]);}
#pythondeflinq56():score_records= [{'Name':"Alice",'Score':50}, {'Name':"Bob",'Score':40}, {'Name':"Cathy",'Score':45}]score_records_dict= {s['Name']:s['Score']forsinscore_records}print("Bob's score: %s"%score_records_dict["Bob"])
Bob's score: {Name: Bob, Score: 40}
This sample filters all elements that matches the type double/float.
//c#staticvoidLinq57(){varnumbers=newobject[]{null,1.0,"two",3,"four",5,"six",7.0};vardoubles=numbers.OfType<double>();Console.WriteLine("Numbers stored as doubles:");doubles.ForEach(Console.WriteLine);}
#pythondeflinq57():numbers= [None,1.0,"two",3,"four",5,"six",7.0]floats= (nforninnumbersifisinstance(n,float))print("Numbers stored as floats:")shared.printN(floats)
Numbers stored as doubles:1.07.0
This sample returns the first matching element as a Product, instead of as a sequence containing a Product.
//c#staticvoidLinq58(){varproducts=GetProductList();varproduct12=products.First(p=>p.ProductID==12);ObjectDumper.Write(product12);}
#pythondeflinq58():products=shared.getProductList()product_12=next(filter(lambdap:p.ProductID==12,products))print(product_12)
{productId: 12, productName: Queso Manchego La Pastora, category: Dairy Products, unitPrice: 38.0, unitsInStock: 86}
This sample finds the first element in the array that starts with 'o'.
//c#staticvoidLinq59(){varstrings=new[]{"zero","one","two","three","four","five","six","seven","eight","nine"};varstartsWithO=strings.First(s=>s.StartsWith('o'));Console.WriteLine("A string starting with 'o': {0}",startsWithO);}
#pythondeflinq59():strings= ["zero","one","two","three","four","five","six","seven","eight","nine"]starts_with_o=next(sforsinstringsifs[0]=='o')print("A string starting with 'o': %s"%starts_with_o)
A string starting with 'o': one
This sample returns the first or default if nothing is found, to try to return the first element of the sequence unless there are no elements, in which case the default value for that type is returned.
//c#staticvoidLinq61(){varnumbers=newint[0];varfirstNumOrDefault=numbers.FirstOrDefault();Console.WriteLine(firstNumOrDefault);}
#pythondeflinq61():numbers= []first_num_or_default=next((nforninnumbers),0)print(first_num_or_default)
0
This sample returns the first or default if nothing is found, to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned.
//c#staticvoidLinq62(){varproducts=GetProductList();varproduct789=products.FirstOrDefault(p=>p.ProductID==789);Console.WriteLine("Product 789 exists: {0}",product789!=null);}
#pythondeflinq62():products=shared.getProductList()product789=next((pforpinproductsifp.ProductID==789),None)print("Product 789 exists: %s"% (product789isnotNone))
Product 789 exists: False
This sample retrieve the second number greater than 5 from an array.
//c#staticvoidLinq64(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varfourthLowNum=numbers.Where(num=>num>5).ElementAt(1);Console.WriteLine("Second number > 5: {0}",fourthLowNum);}
#pythondeflinq64():numbers= [5,4,1,3,9,8,6,7,2,0]second_number_greater_than_5= [nforninnumbersifn>5][1]print("Second number > 5: %d"%second_number_greater_than_5)
Second number > 5: 8
This sample uses generates a sequence of numbers from 100 to 149 that is used to find which numbers in that range are odd and even.
//c#staticvoidLinq65(){varnumbers=Enumerable.Range(100,50).Select(n=>new{Number=n,OddEven=n%2==1?"odd":"even"});numbers.ForEach((n)=>Console.WriteLine("The number {0} is {1}.",n.Number,n.OddEven));}
#pythondeflinq65():numbers=range(100,150)odd_even= ({'Number':n,'OddEven': ("odd"if (n%2==1)else"even")}forninnumbers)foriteminodd_even:print("The number %s is %s"% (item['Number'],item['OddEven']))
The number 100 is even.The number 101 is odd.The number 102 is even.The number 103 is odd.The number 104 is even.The number 105 is odd.The number 106 is even.The number 107 is odd.The number 108 is even.The number 109 is odd.The number 110 is even....
This sample uses generates a sequence of repeated numbers that contains the number 7 ten times.
//c#staticvoidLinq66(){varnumbers=Enumerable.Repeat(7,10);numbers.ForEach(Console.WriteLine);}
#pythondeflinq66():numbers=itertools.repeat(7,10)shared.printN(numbers)
7777777777
This sample uses determines if Any of the words in the array contain the substring 'ei'.
//c#staticvoidLinq67(){varwords=new[]{"believe","relief","receipt","field"};variAfterE=words.Any(w=>w.Contains("ei"));Console.WriteLine($"There is a word in the list that contains 'ei':{iAfterE}");}
#pythondeflinq67():words= ["believe","relief","receipt","field"]i_after_e=any("ei"inwforwinwords)print("There is a word that contains in the list that contains 'ei': %s"%i_after_e)
There is a word that contains in the list that contains 'ei': true
This sample determines if Any of the grouped a list of products only for categories that have at least one product that is out of stock.
//c#staticvoidLinq69(){varproducts=GetProductList();varproductGroups=products.GroupBy(prod=>prod.Category).Where(prodGroup=>prodGroup.Any(p=>p.UnitsInStock==0)).Select(prodGroup=>new{Category=prodGroup.Key,Products=prodGroup});ObjectDumper.Write(productGroups,1);}
#pythondeflinq69():pass
{Category: Condiments, Products: {{productId: 3, productName: Aniseed Syrup, category: Condiments, unitPrice: 10.0, unitsInStock: 13}, {productId: 4, productName: Chef Anton's Cajun Seasoning, category: Condiments, unitPrice: 22.0, unitsInStock: 53}, {productId: 5, productName: Chef Anton's Gumbo Mix, category: Condiments, unitPrice: 21.35, unitsInStock: 0}, {productId: 6, productName: Grandma's Boysenberry Spread, category: Condiments, unitPrice: 25.0, unitsInStock: 120}, {productId: 8, productName: Northwoods Cranberry Sauce, category: Condiments, unitPrice: 40.0, unitsInStock: 6}, {productId: 15, productName: Genen Shouyu, category: Condiments, unitPrice: 15.5, unitsInStock: 39}, {productId: 44, productName: Gula Malacca, category: Condiments, unitPrice: 19.45, unitsInStock: 27}, {productId: 61, productName: Sirop d'�rable, category: Condiments, unitPrice: 28.5, unitsInStock: 113}, {productId: 63, productName: Vegie-spread, category: Condiments, unitPrice: 43.9, unitsInStock: 24}, {productId: 65, productName: Louisiana Fiery Hot Pepper Sauce, category: Condiments, unitPrice: 21.05, unitsInStock: 76}, {productId: 66, productName: Louisiana Hot Spiced Okra, category: Condiments, unitPrice: 17.0, unitsInStock: 4}, {productId: 77, productName: Original Frankfurter gr�ne So�e, category: Condiments, unitPrice: 13.0, unitsInStock: 32}}}...
This sample determines if All the elements in the array contain only odd numbers.
//c#staticvoidLinq70(){varnumbers=new[]{1,11,3,19,41,65,19};varonlyOdd=numbers.All(n=>n%2==1);Console.WriteLine($"The list contains only odd numbers:{onlyOdd}");}
#pythondeflinq70():numbers= [1,11,3,19,41,65,19]only_odd=all(n%2==1forninnumbers)print("The list contains only odd numbers: %s"%only_odd)
The list contains only odd numbers: true
This sample determines if All elements in the grouped a list of products by categories, have all of their products in stock.
//c#staticvoidLinq72(){varproducts=GetProductList();varproductGroups=products.GroupBy(prod=>prod.Category).Where(prodGroup=>prodGroup.All(p=>p.UnitsInStock>0)).Select(prodGroup=>new{Category=prodGroup.Key,Products=prodGroup});ObjectDumper.Write(productGroups,1);}
#pythondeflinq72():pass
{Category: Grains/Cereals, Products: {{productId: 22, productName: Gustaf's Kn�ckebr�d, category: Grains/Cereals, unitPrice: 21.0, unitsInStock: 104}, {productId: 23, productName: Tunnbr�d, category: Grains/Cereals, unitPrice: 9.0, unitsInStock: 61}, {productId: 42, productName: Singaporean Hokkien Fried Mee, category: Grains/Cereals, unitPrice: 14.0, unitsInStock: 26}, {productId: 52, productName: Filo Mix, category: Grains/Cereals, unitPrice: 7.0, unitsInStock: 38}, {productId: 56, productName: Gnocchi di nonna Alice, category: Grains/Cereals, unitPrice: 38.0, unitsInStock: 21}, {productId: 57, productName: Ravioli Angelo, category: Grains/Cereals, unitPrice: 19.5, unitsInStock: 36}, {productId: 64, productName: Wimmers gute Semmelkn�del, category: Grains/Cereals, unitPrice: 33.25, unitsInStock: 22}}}...
This sample gets the number of unique prime factors of 300.
//c#staticvoidLinq73(){varprimeFactorsOf300=new[]{2,2,3,5,5};varuniqueFactors=primeFactorsOf300.Distinct().Count();Console.WriteLine($"There are{uniqueFactors} unique prime factors of 300.");}
#pythondeflinq73():factors_of_300= [2,2,3,5,5]unique_factors=len(set(factors_of_300))print("There are %d unique factors of 300."%unique_factors)
There are 3 unique factors of 300.
This sample gets the number of odd ints in the array.
//c#staticvoidLinq74(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varoddNumbers=numbers.Count(n=>n%2==1);Console.WriteLine($"There are{oddNumbers} odd numbers in the list.");}
#pythondeflinq74():numbers= [5,4,1,3,9,8,6,7,2,0]odd_numbers=sum(n%2==1forninnumbers)print("There are %d odd numbers in the list."%odd_numbers)
There are 5 odd numbers in the list.
This sample uses returns a list of customers and how many orders each has.
//c#staticvoidLinq76(){varcustomers=GetCustomerList();varorderCounts=customers.Select(cust=>new{cust.CustomerID,OrderCount=cust.Orders.Count()});ObjectDumper.Write(orderCounts);}
#pythondeflinq76():customers=shared.getCustomerList()order_counts=map(lambdacust:SimpleNamespace(CustomerID=cust.CustomerID,OrderCount=len(cust.Orders)),customers)shared.print_namespace(order_counts)
{CustomerId: ALFKI, OrderCount: 6}{CustomerId: ANATR, OrderCount: 4}{CustomerId: ANTON, OrderCount: 7}{CustomerId: AROUT, OrderCount: 13}{CustomerId: BERGS, OrderCount: 18}{CustomerId: BLAUS, OrderCount: 7}{CustomerId: BLONP, OrderCount: 11}...
This sample uses returns a list of categories and how many products each has.
//c#staticvoidLinq77(){varproducts=GetProductList();varcategoryCounts=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{Category=prodGroup.Key,ProductCount=prodGroup.Count()});ObjectDumper.Write(categoryCounts);}
#pythondeflinq77():products=shared.getProductList()sorted_by_category=sorted(products,key=lambdap:p.Category)grouped_by_category=groupby(sorted_by_category,key=lambdap:p.Category)category_counts=map(lambdag:SimpleNamespace(Category=g[0],ProductCount=len(list(g[1]))),grouped_by_category)shared.print_namespace(category_counts)
{Category: Dairy Products, ProductCount: 10}{Category: Grains/Cereals, ProductCount: 7}{Category: Confections, ProductCount: 13}{Category: Seafood, ProductCount: 12}{Category: Condiments, ProductCount: 12}{Category: Meat/Poultry, ProductCount: 6}{Category: Produce, ProductCount: 5}{Category: Beverages, ProductCount: 12}
This sample uses adds all the numbers in an array.
//c#staticvoidLinq78(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varnumSum=numbers.Sum();Console.WriteLine($"The sum of the numbers is{numSum}.");}
#pythondeflinq78():numbers= [5,4,1,3,9,8,6,7,2,0]num_sum=sum(numbers)print("The sum of the numbers is %d."%num_sum)
The sum of the numbers is 45.
This sample gets the total number of characters of all words in the array.
//c#staticvoidLinq79(){varwords=new[]{"cherry","apple","blueberry"};vartotalChars=words.Sum(w=>w.Length);Console.WriteLine($"There are a total of{totalChars} characters in these words.");}
#pythondeflinq79():words= ["cherry","apple","blueberry"]total_chars=sum(len(w)forwinwords)print("There are a total of %d characters in these words."%total_chars)
There are a total of 20 characters in these words.
This sample gets the total units in stock for each product category.
//c#staticvoidLinq80(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{Category=prodGroup.Key,TotalUnitsInStock=prodGroup.Sum(p=>p.UnitsInStock)});ObjectDumper.Write(categories);}
#pythondeflinq80():products=shared.getProductList()sorted_by_category=sorted(products,key=lambdap:p.Category)grouped_by_category=groupby(sorted_by_category,key=lambdap:p.Category)category_counts=map(lambdag:SimpleNamespace(Category=g[0],TotalUnitsInStock=sum(p.UnitsInStockforping[1])),grouped_by_category)shared.print_namespace(category_counts)
{Category: Dairy Products, TotalUnitsInStock: 393}{Category: Grains/Cereals, TotalUnitsInStock: 308}{Category: Confections, TotalUnitsInStock: 386}{Category: Seafood, TotalUnitsInStock: 701}{Category: Condiments, TotalUnitsInStock: 507}{Category: Meat/Poultry, TotalUnitsInStock: 165}{Category: Produce, TotalUnitsInStock: 100}{Category: Beverages, TotalUnitsInStock: 559}
This sample uses gets the lowest number in an array.
//c#staticvoidLinq81(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varminNum=numbers.Min();Console.WriteLine($"The minimum number is{minNum}.");}
#pythondeflinq81():numbers= [5,4,1,3,9,8,6,7,2,0]min_num=min(numbers)print("The minimum number is %d"%min_num)
The minimum number is 0.
This sample uses gets the length of the shortest word in an array.>
//c#staticvoidLinq82(){varwords=new[]{"cherry","apple","blueberry"};varshortestWord=words.Min(w=>w.Length);Console.WriteLine($"The shortest word is{shortestWord} characters long.");}
#pythondeflinq82():words= ["cherry","apple","blueberry"]shortest_word=min(len(w)forwinwords)print("The shortest word is %d characters long."%shortest_word)
The shortest word is 5 characters long.
This sample uses gets the cheapest price among each category's products.
//c#staticvoidLinq83(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{Category=prodGroup.Key,CheapestPrice=prodGroup.Min(p=>p.UnitPrice)});ObjectDumper.Write(categories);}
#pythondeflinq83():products=shared.getProductList()sorted_by_category=sorted(products,key=lambdap:p.Category)grouped_by_category=groupby(sorted_by_category,key=lambdap:p.Category)category_cheapest_price=map(lambdag:SimpleNamespace(Category=g[0],CheapestPrice=min(p.UnitPriceforping[1])),grouped_by_category)shared.print_namespace(category_cheapest_price)
{Category: Dairy Products, CheapestPrice: 2.5}{Category: Grains/Cereals, CheapestPrice: 7.0}{Category: Confections, CheapestPrice: 9.2}{Category: Seafood, CheapestPrice: 6.0}{Category: Condiments, CheapestPrice: 10.0}{Category: Meat/Poultry, CheapestPrice: 7.45}{Category: Produce, CheapestPrice: 10.0}{Category: Beverages, CheapestPrice: 4.5}
This sample gets the products with the lowest price in each category.
//c#staticvoidLinq84(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{prodGroup,minPrice=prodGroup.Min(p=>p.UnitPrice)}).Select(x=>new{Category=x.prodGroup.Key,CheapestProducts=x.prodGroup.Where(p=>p.UnitPrice==x.minPrice)});ObjectDumper.Write(categories,1);}
#pythondeflinq84():pass
{Category: Dairy Products, CheapestProducts: {{productId: 33, productName: Geitost, category: Dairy Products, unitPrice: 2.5, unitsInStock: 112}}}{Category: Grains/Cereals, CheapestProducts: {{productId: 52, productName: Filo Mix, category: Grains/Cereals, unitPrice: 7.0, unitsInStock: 38}}}{Category: Confections, CheapestProducts: {{productId: 19, productName: Teatime Chocolate Biscuits, category: Confections, unitPrice: 9.2, unitsInStock: 25}}}{Category: Seafood, CheapestProducts: {{productId: 13, productName: Konbu, category: Seafood, unitPrice: 6.0, unitsInStock: 24}}}{Category: Condiments, CheapestProducts: {{productId: 3, productName: Aniseed Syrup, category: Condiments, unitPrice: 10.0, unitsInStock: 13}}}{Category: Meat/Poultry, CheapestProducts: {{productId: 54, productName: Tourti�re, category: Meat/Poultry, unitPrice: 7.45, unitsInStock: 21}}}{Category: Produce, CheapestProducts: {{productId: 74, productName: Longlife Tofu, category: Produce, unitPrice: 10.0, unitsInStock: 4}}}{Category: Beverages, CheapestProducts: {{productId: 24, productName: Guaran� Fant�stica, category: Beverages, unitPrice: 4.5, unitsInStock: 20}}}
This sample gets the highest number in an array. Note that the method returns a single value.
//c#staticvoidLinq85(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varmaxNum=numbers.Max();Console.WriteLine($"The maximum number is{maxNum}.");}
#pythondeflinq85():numbers= [5,4,1,3,9,8,6,7,2,0]max_num=max(numbers)print("The maximum number is %d."%max_num)
The maximum number is 9.
This sample gets the length of the longest word in an array.
//c#staticvoidLinq86(){varwords=new[]{"cherry","apple","blueberry"};varlongestLength=words.Max(w=>w.Length);Console.WriteLine($"The longest word is{longestLength} characters long.");}
#pythondeflinq86():words= ["cherry","apple","blueberry"]longest_word=max(len(w)forwinwords)print("The longest word is %d characters long."%longest_word)
The longest word is 9 characters long.
This sample gets the most expensive price among each category's products.
//c#staticvoidLinq87(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{Category=prodGroup.Key,MostExpensivePrice=prodGroup.Max(p=>p.UnitPrice)});ObjectDumper.Write(categories);}
#pythondeflinq87():products=shared.getProductList()sorted_by_category=sorted(products,key=lambdap:p.Category)grouped_by_category=groupby(sorted_by_category,key=lambdap:p.Category)category_expensive_price=map(lambdag:SimpleNamespace(Category=g[0],MostExpensive=max(p.UnitPriceforping[1])),grouped_by_category)shared.print_namespace(category_expensive_price)
{Category: Dairy Products, MostExpensivePrice: 55.0}{Category: Grains/Cereals, MostExpensivePrice: 38.0}{Category: Confections, MostExpensivePrice: 81.0}{Category: Seafood, MostExpensivePrice: 62.5}{Category: Condiments, MostExpensivePrice: 43.9}{Category: Meat/Poultry, MostExpensivePrice: 123.79}{Category: Produce, MostExpensivePrice: 53.0}{Category: Beverages, MostExpensivePrice: 263.5}
This sample gets the products with the most expensive price in each category.
//c#staticvoidLinq88(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{prodGroup,maxPrice=prodGroup.Max(p=>p.UnitPrice)}).Select(x=>new{Category=x.prodGroup.Key,MostExpensiveProducts=x.prodGroup.Where(p=>p.UnitPrice==x.maxPrice)});ObjectDumper.Write(categories,1);}
#pythondeflinq88():pass
{Category: Dairy Products, MostExpensiveProducts: {{productId: 59, productName: Raclette Courdavault, category: Dairy Products, unitPrice: 55.0, unitsInStock: 79}}}{Category: Grains/Cereals, MostExpensiveProducts: {{productId: 56, productName: Gnocchi di nonna Alice, category: Grains/Cereals, unitPrice: 38.0, unitsInStock: 21}}}{Category: Confections, MostExpensiveProducts: {{productId: 20, productName: Sir Rodney's Marmalade, category: Confections, unitPrice: 81.0, unitsInStock: 40}}}{Category: Seafood, MostExpensiveProducts: {{productId: 18, productName: Carnarvon Tigers, category: Seafood, unitPrice: 62.5, unitsInStock: 42}}}{Category: Condiments, MostExpensiveProducts: {{productId: 63, productName: Vegie-spread, category: Condiments, unitPrice: 43.9, unitsInStock: 24}}}{Category: Meat/Poultry, MostExpensiveProducts: {{productId: 29, productName: Th�ringer Rostbratwurst, category: Meat/Poultry, unitPrice: 123.79, unitsInStock: 0}}}{Category: Produce, MostExpensiveProducts: {{productId: 51, productName: Manjimup Dried Apples, category: Produce, unitPrice: 53.0, unitsInStock: 20}}}{Category: Beverages, MostExpensiveProducts: {{productId: 38, productName: C�te de Blaye, category: Beverages, unitPrice: 263.5, unitsInStock: 17}}}
This sample gets the average of all numbers in an array.
//c#staticvoidLinq89(){varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varaverageNum=numbers.Average();Console.WriteLine($"The average number is{averageNum}.");}
#pythondeflinq89():numbers= [5,4,1,3,9,8,6,7,2,0]average_num=sum(numbers)/float(len(numbers))print("The average number is %f."%average_num)
The average number is 4.5.
This sample gets the average length of the words in the array.
//c#staticvoidLinq90(){varwords=new[]{"cherry","apple","blueberry"};varaverageLength=words.Average(w=>w.Length);Console.WriteLine($"The average word length is{averageLength} characters.");}
#pythondeflinq90():words= ["cherry","apple","blueberry"]average_length=sum(len(w)forwinwords)/float(len(words))print("The average word length is %f characters."%average_length)
The average word length is 6.666666666666667 characters.
This sample gets the average price of each category's products.
//c#staticvoidLinq91(){varproducts=GetProductList();varcategories=products.GroupBy(prod=>prod.Category).Select(prodGroup=>new{Category=prodGroup.Key,AveragePrice=prodGroup.Average(p=>p.UnitPrice)});ObjectDumper.Write(categories);}
#pythondeflinq91():pass
{Category: Dairy Products, AveragePrice: 28.73}{Category: Grains/Cereals, AveragePrice: 20.25}{Category: Confections, AveragePrice: 25.16}{Category: Seafood, AveragePrice: 20.6825}{Category: Condiments, AveragePrice: 23.0625}{Category: Meat/Poultry, AveragePrice: 54.00666666666667}{Category: Produce, AveragePrice: 32.37}{Category: Beverages, AveragePrice: 37.979166666666664}
This sample uses creates a running product on the array that calculates the total product of all elements.
//c#staticvoidLinq92(){vardoubles=new[]{1.7,2.3,1.9,4.1,2.9};varproduct=doubles.Aggregate((runningProduct,nextFactor)=>runningProduct*nextFactor);Console.WriteLine($"Total product of all numbers:{product}");}
#pythondeflinq92():doubles= [1.7,2.3,1.9,4.1,2.9]product=reduce(operator.mul,doubles)#or#product = reduce(lambda running_product, next_factor: running_product * next_factor, doubles)print("Total product of all numbers: %f"%product)
Total product of all numbers: 88.33080999999999
This sample uses to creates a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0.
//c#staticvoidLinq93(){varstartBalance=100.0;varattemptedWithdrawals=new[]{20,10,40,50,10,70,30};varendBalance=attemptedWithdrawals.Aggregate(startBalance,(balance,nextWithdrawal)=>((nextWithdrawal<=balance)?(balance-nextWithdrawal):balance));Console.WriteLine($"Ending balance:{endBalance}");}
#pythondeflinq93():start_balance=100.0attempted_withdrawals= [20,10,40,50,10,70,30]end_balance=reduce(lambdarunningBalance,nextWithDrawal:runningBalance-nextWithDrawalifnextWithDrawal<=runningBalanceelserunningBalance,attempted_withdrawals,start_balance)print("Ending balance: %f"%end_balance)
Ending balance: 20.0
This sample creates a contatenation of each array's values, one after the other.
//c#staticvoidLinq94(){int[]numbersA={0,2,4,5,6,8,9};int[]numbersB={1,3,5,7,8};varallNumbers=numbersA.Concat(numbersB);Console.WriteLine("All numbers from both arrays:");allNumbers.ForEach(Console.WriteLine);}
#pythondeflinq94():numbers_a= [0,2,4,5,6,8,9]numbers_b= [1,3,5,7,8]all_numbers=numbers_a+numbers_bprint("All numbers from both arrays:")shared.printN(all_numbers)
All numbers from both arrays:024568913578
This sample creates a contatenation that contains the names of all customers and products, including any duplicates.
//c#staticvoidLinq95(){varcustomers=GetCustomerList();varproducts=GetProductList();varcustomerNames=customers.Select(cust=>cust.CompanyName);varproductNames=products.Select(prod=>prod.ProductName);varallNames=customerNames.Concat(productNames);Console.WriteLine("Customer and product names:");allNames.ForEach(Console.WriteLine);}
#pythondeflinq95():products=shared.getProductList()customers=shared.getCustomerList()customer_names= [p.ProductNameforpinproducts]product_names= [c.CompanyNameforcincustomers]all_names=customer_names+product_namesprint("Customer and product names:")shared.printS(all_names)
Customer and product names:Alfreds FutterkisteAna Trujillo Emparedados y heladosAntonio Moreno Taquer�aAround the HornBerglunds snabbk�pBlauer See Delikatessen...
This sample checks if two sequences match on all elements in the same order
//c#staticvoidLinq96(){varwordsA=new[]{"cherry","apple","blueberry"};varwordsB=new[]{"cherry","apple","blueberry"};varmatch=wordsA.SequenceEqual(wordsB);Console.WriteLine($"The sequences match:{match}");}
#pythondeflinq96():words_a= ["cherry","apple","blueberry"]words_b= ["cherry","apple","blueberry"]match=words_a==words_bprint("The sequences match: %s"%match)
The sequences match: True
This sample checks if two sequences match on all elements in the same order.
//c#staticvoidLinq97(){varwordsA=new[]{"cherry","apple","blueberry"};varwordsB=new[]{"apple","blueberry","cherry"};varmatch=wordsA.SequenceEqual(wordsB);Console.WriteLine($"The sequences match:{match}");}
#pythondeflinq97():words_a= ["cherry","apple","blueberry"]words_b= ["apple","blueberry","cherry"]match=words_a==words_bprint("The sequences match: %s"%match)
The sequences match: False
The following sample shows how query execution is deferred until the query is enumerated at a foreach statement.
//c#staticvoidLinq99(){// Queries are not executed until you enumerate over them.varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};inti=0;varsimpleQuery=numbers.Select(x=>i++);// The local variable 'i' is not incremented until the query is executed in the foreach loop.Console.WriteLine($"The current value of i is{i}");//i is still zerosimpleQuery.ForEach(item=>Console.WriteLine($"v ={item}, i ={i}"));// now i is incremented}
#pythondeflinq99():numbers= [5,4,1,3,9,8,6,7,2,0]i=0defadd_to_i(n):nonlocalii=i+1returnnq=map(add_to_i,numbers)forvinq:print("v = %d, i = %d"% (v,i))
v = 1, i = 1v = 2, i = 2v = 3, i = 3v = 4, i = 4v = 5, i = 5v = 6, i = 6v = 7, i = 7v = 8, i = 8v = 9, i = 9v = 10, i = 10
The following sample shows how queries can be executed immediately, and their results stored in memory, with methods such as ToList/list.
//c#staticvoidLinq100(){// Methods like ToList(), Max(), and Count() cause the query to be executed immediately.varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};vari=0;varimmediateQuery=numbers.Select(x=>++i).ToList();Console.WriteLine("The current value of i is {0}",i);//i has been incrementedimmediateQuery.ForEach(item=>Console.WriteLine($"v ={item}, i ={i}"));}
#pythondeflinq100():numbers= [5,4,1,3,9,8,6,7,2,0]i=0defadd_to_i(n):nonlocalii=i+1returnnq=list(map(add_to_i,numbers))forvinq:print("v = %d, i = %d"% (v,i))
v = 1, i = 10v = 2, i = 10v = 3, i = 10v = 4, i = 10v = 5, i = 10v = 6, i = 10v = 7, i = 10v = 8, i = 10v = 9, i = 10v = 10, i = 10
The following sample shows how, because of deferred execution, queries can be used again after data changes and will then operate on the new data.
//c#staticvoidLinq101(){// Deferred execution lets us define a query once and then reuse it later in various ways.varnumbers=new[]{5,4,1,3,9,8,6,7,2,0};varlowNumbers=numbers.Where(num=>num<=3);Console.WriteLine("First run numbers <= 3:");lowNumbers.ForEach(Console.WriteLine);// Modify the source data.for(vari=0;i<10;i++){numbers[i]=-numbers[i];}// During this second run, the same query object,// lowNumbers, will be iterating over the new state// of numbers[], producing different results:Console.WriteLine("Second run numbers <= 3:");lowNumbers.ForEach(Console.WriteLine);}
#pythondeflinq101():pass
First run numbers <= 3:1320Second run numbers <= 3:-5-4-1-3-9-8-6-7-20
About
Python Linq Examples: Comparision of C# Linq functional programming to Python
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.