-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
850 lines (689 loc) · 29.1 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Reflection;
namespace DelegatesLambdasEvents
{
delegate void MeDelegate();
delegate bool VerifcationMethod(int number);
delegate T GenericDelegate<T>();
delegate void BaseDelegate(Base b);
delegate void DerivedDelegate(Derived d);
delegate Base ReturnBaseObj();
delegate Derived ReturnDerivedObj();
delegate string MeDelegateTakeStringReturnString(string param);
public enum Volume
{
Loud,
Louder,
TheLoudest
}
public class CustomizedEventArgs : EventArgs
{
private Volume vol;
public Volume ReturnVol()
{
return this.vol;
}
public CustomizedEventArgs(Volume vol)
{
this.vol = vol;
}
}
class NoSugar
{
int i = 10;
public void IncrementI()
{
i++;
}
public void IncrementIByTwo()
{
i += 2;
}
}
class Base { }
class Derived : Base { }
class Program
{
public static void CheckVolume(object obj, CustomizedEventArgs arg)
{
Subject s = obj as Subject;
Console.WriteLine("Name: " + s.Name);
if (arg.ReturnVol().Equals(Volume.Loud))
{
Console.WriteLine("It's not so bad");
}
else if (arg.ReturnVol().Equals(Volume.Louder))
{
Console.WriteLine("It's too loud!");
}
}
static IEnumerable<int> SelectedNumbers(IEnumerable<int> list, VerifcationMethod verify)
{
IEnumerable<int> results = null;
foreach (int elem in list)
{
if (verify(elem))
yield return elem;
}
}
public bool VerifyIfNumberIsBiggerThan(int number)
{
return number > 10;
}
static void MyMethod()
{
Console.WriteLine("I'm my method and I was assigned to MyDelegate");
}
static Random Random = new Random();
string ReturnName(string name)
{
return "My name is " + name;
}
static void ConsumeAndInvokeMethod(MeDelegate md)
{
md.Invoke();
}
//int returnHighestPrime(int i)
//{
// List<int> results = new List<int>();
// int d = 2;
// while (i > 1)
// {
// while (i % 2 == 0)
// {
// results.Add(i);
// i /= d;
// }
// d++;
// }
// return results.
//}
static int returnTen() { return 5; }
static int returnTwenty() { return 20; }
static void Main(string[] args)
{
MeDelegate Md = new MeDelegate(MyMethod);
Md += MyMethod;
Console.WriteLine("***********");
Console.WriteLine("Latest added method to Md delegate: " + Md.Method);
Console.WriteLine("Target of Md delegate: " + Md.Target);
Md += () => Console.WriteLine("I'm coming from lambda expression");
Console.WriteLine("After adding lambda: " + Md.Method);
//ConsumeAndInvokeMethod(Md);
//ConsumeAndInvokeMethod(new MeDelegate(() => Console.WriteLine("What am I doing here!?")));
//Md.Invoke();
//MeDelegateTakeStringReturnString Mdstr = (name) => { return "My name is:" + name; };
//Console.WriteLine(Mdstr("Don Juan"));
MeDelegateTakeStringReturnString Mdstr = new Program().ReturnName;
Console.WriteLine(Mdstr("Tomek"));
Console.WriteLine("Small check for Mdstr - target: " + Mdstr.Target + " || method: " + Mdstr.Method);
if (Mdstr.Method.ToString().Equals("System.String ReturnName(System.String)"))
Console.WriteLine("Oh my god, return type for Mdstr delegate is a string!");
else
Console.WriteLine("I don't know what is it !");
IEnumerable<int> NumbersBiggerThanTen = SelectedNumbers(new[] { 1, 2, 3, 10, 15, 25, 276, 326 }, new Program().VerifyIfNumberIsBiggerThan);
Console.WriteLine("****************");
foreach (int number in NumbersBiggerThanTen)
{
Console.WriteLine("Number bigger than five: " + number);
}
Console.WriteLine("Invocation of SelectedNumbers method with using lambda method");
IEnumerable<int> NumbersBiggerThan200 = SelectedNumbers(new[] { 1, 2, 3, 10, 15, 25, 276, 326 }, (n) => n > 200);
foreach (int number in NumbersBiggerThan200)
{
Console.WriteLine("Number bigger than two hundread: " + number);
}
Console.WriteLine("********************");
Console.WriteLine("************DELEGATE CHAINING***********");
MeDelegate delegateChain = () => Console.WriteLine("First method");
delegateChain += () => Console.WriteLine("Second method method in chain");
delegateChain += MyMethod;
//Last delegate in chain returns value
Console.WriteLine("Invoke chain");
Console.WriteLine("####################");
foreach (MeDelegate md in delegateChain.GetInvocationList())
{
Console.WriteLine("Method: " + md.Method + " , target: " + md.Target);
}
Console.WriteLine("*****");
Console.WriteLine("Generic delegate in action");
static IEnumerable<TArgs> InvokeChain<TArgs>(GenericDelegate<TArgs> genDel)
{
foreach (GenericDelegate<TArgs> del in genDel.GetInvocationList())
{
yield return del();
}
}
static IEnumerable<TArgs> InvokeFuncChain<TArgs>(Func<TArgs> genDel)
{
foreach (Func<TArgs> del in genDel.GetInvocationList())
{
yield return del();
}
}
GenericDelegate<int> GenDel = returnTen;
GenDel += returnTwenty;
IEnumerable<int> resultsForGenericChain = InvokeChain<int>(GenDel);
foreach (int i in resultsForGenericChain)
{
Console.WriteLine("Result from generic chain: " + i);
}
static IEnumerable<TReturn> InvokeLambdasFromAFuncDelegate<TArgs, TReturn>(Func<TArgs, TReturn> func, TArgs number)
{
foreach (Func<TArgs, TReturn> f in func.GetInvocationList())
{
yield return f(number);
}
}
/**
* Func and Action
*/
Console.WriteLine("***************");
Console.WriteLine("Func and Action delegates");
Func<int> FuncChain = returnSixteen;
Func<int, bool> TakeIntReturnBool = null;
TakeIntReturnBool += (n) => n > 30;
TakeIntReturnBool += (n) => n < 50;
FuncChain += returnSixty;
FuncChain += () => 666;
FuncChain += () => 69;
static int returnSixteen() { return 16; }
static int returnSixty() { return 60; }
resultsForGenericChain = InvokeFuncChain<int>(FuncChain);
foreach (int i in resultsForGenericChain)
{
Console.WriteLine("Result from generic chain: " + i);
}
//IEnumerable<bool> tableOfTruth= InvokeLambdasFromAFuncDelegate<int, bool>(TakeIntReturnBool, 60);
//foreach(bool b in tableOfTruth)
//{
// Console.WriteLine("Table of truth says: " + b);
//}
//We can use something else
foreach (bool b in InvokeLambdasFromAFuncDelegate(TakeIntReturnBool, 60))
{
Console.WriteLine("Table of truth says: " + b);
};
//Annonymous Methods
Func<int, bool> f = delegate (int i) { return i > 10; };
Console.WriteLine("Anonymous method: " + f(30));
//Closures
Action ReturnAction()
{
int i = 0;
return () => i++;
}
Action ReturnBlendedAction()
{
Action a = null;
int i = 0;
a += () =>
{
Console.WriteLine("First method");
i++;
Console.WriteLine("i value: " + i);
};
a += () =>
{
Console.WriteLine("Second method");
i++;
Console.WriteLine("i value: " + i);
};
return a;
}
Action SugarizedSyntax()
{
Action a = null;
int i = 0;
a += () => i++;
a += () => i += 5;
return a;
}
Action UnsugarizedSyntax()
{
Action foo = null;
var ns = new NoSugar();
foo += ns.IncrementI;
foo += ns.IncrementIByTwo;
return foo;
}
Action FirstAction = ReturnAction();
Action SecondAction = ReturnAction();
FirstAction(); FirstAction();
SecondAction();
Action FirstBlend = ReturnBlendedAction();
FirstBlend();
FirstBlend();
FirstBlend();
FirstBlend();
Action UnsugarizedActionOne = UnsugarizedSyntax();
Action UnsugarizedActionTwo = UnsugarizedSyntax();
UnsugarizedActionOne();
UnsugarizedActionTwo();
UnsugarizedActionOne();
UnsugarizedActionTwo();
//Observer pattern
Subject sub = new Subject();
new Listener(sub);
new Listener(sub);
new Listener(sub);
new Listener(sub);
sub.InvokeAction();
//Events
//Action can be called directly - events not
//Action can be directly assigned to null - events cant be assigned to null directly [ but u can add as many methods as u wish ]
static void MethodHandlerSubstitue(object s, EventArgs ea)
{
Subject sub = s as Subject;
Console.WriteLine("My name is: "+sub.Name);
}
Subject secSub = new Subject() { Name = "Dorothy"};
Subject thirdSub = new Subject() { Name = "Judy"};
secSub.TriggerListenersByEventHandler += MethodHandlerSubstitue;
thirdSub.TriggerListenersByEventHandler += MethodHandlerSubstitue;
secSub.BeTippedOver();
thirdSub.BeTippedOver();
Console.WriteLine("************************************");
Console.WriteLine("***********Event handlers in action**************");
Subject objectWithEventHandlers = new Subject();
objectWithEventHandlers.EventHandlerWithEventArgs += CheckVolume;
objectWithEventHandlers.CalEventHandlerWithEventArgs();
/**
* Delegate contravariance
*/
static void TakeBase(Base b) { }
static void TakeDerived(Derived d) { }
static Base ReturnBase() { return null; }
static Derived ReturnDerived() { return null; }
BaseDelegate bd1 = TakeBase;
//Line below it's not valid one
//BaseDelegate bd2 = TakeDerived;
bd1(new Base());
bd1(new Derived());
DerivedDelegate dd1 = TakeBase;
DerivedDelegate dd2 = TakeDerived;
//Invalid, cause of contravariance
//dd1(new Base());
dd1(new Derived());
dd2(new Derived());
//Invalid
//dd2(new Base());
/**
* Delegate contravariance
*/
ReturnBaseObj RetBaseObj;
ReturnDerivedObj RetDerObj;
RetBaseObj = ReturnBase;
RetBaseObj = ReturnDerived;
//Invalid line, return type is not specific
//RetDerObj = ReturnBase;
RetDerObj = ReturnDerived;
//Extension methods
DateTime MartasBday = DateTime.Parse("14/10/2020");
DateTime time = DateTime.Parse("10:00pm");
DateTime combined1 = ExtensionMethods.Combine(MartasBday, time);
DateTime combined2 = MartasBday.Combine(time);
Console.WriteLine("Made from two args: " + combined1);
Console.WriteLine("Made from extension method invoked from datetime object: " + combined2);
//LINQ Introduction
int[] numbers = new[] { 3, 4, 5, 10, 23, 333 };
var result =
from n in numbers
where n % 2 == 0
select n;
var resultsFromMethod =
numbers.Where(n => n > 10)
.Select(n => n);
var results =
Enumerable.Select(
Enumerable.Where(numbers, n => n > 10),
n => n);
var resultsFromMyExtension =
numbers.Where(n => n > 0);
//We are able to omit this Select clause
//.Select(n => n);
foreach (var res in results)
{
Console.WriteLine("Result: " + res);
}
foreach (var res in resultsFromMyExtension)
{
Console.WriteLine("Result: " + res);
}
Console.WriteLine("***************************");
Console.WriteLine("***************************");
Console.WriteLine("***************************");
Console.WriteLine("***************************");
Console.WriteLine("DEFERRED EXECUTION!!!!");
int[] randomNumbers = { 1, 2, 3, 4, 5, 6, 11, 12, 15 };
//Due to some reason it doesnt work
//var results = randomNumbers.Where(t => t > 5).Select(t => t);
//Dependency injection
//Create an instance of a class using Activator class
//var msgService = new MessageService();
//var serviceByActivator =(HelloService)Activator.CreateInstance(typeof(HelloService));
//There is no parameterless constructor, so need to pass ct arg to CreateInstance method
//var consumerByActivator = (ServiceConsumer)Activator.CreateInstance(typeof(ServiceConsumer),((HelloService)Activator.CreateInstance(typeof(HelloService),msgService)));
//foreach(Object o in typeof(ServiceConsumer).GetConstructors())
//{
// ConstructorInfo c = (ConstructorInfo)o;
// var par= c.GetParameters();
// foreach (Object x in par)
// {
// Console.WriteLine(x);
// }
//}
//var singleConstructor = typeof(ServiceConsumer).GetConstructors().Single();
var type = typeof(HelloService);
//serviceByActivator.Print();
var container = new DependencyContainer();
container.AddTransient<HelloService>();
container.AddTransient<ServiceConsumer>();
container.AddSingleton<MessageService>();
Console.WriteLine("Count for dependencies: " + container._dependencies.Count);
var resolver = new DependencyResolver(container);
var consumer1 = resolver.GetService<ServiceConsumer>();
var consumer2 = resolver.GetService<ServiceConsumer>();
var consumer3 = resolver.GetService<ServiceConsumer>();
consumer1.Print();
consumer2.Print();
consumer3.Print();
//var resolvedService = resolver.GetService<ServiceConsumer>();
Console.WriteLine("*****************************");
Console.WriteLine("*****************************");
Console.WriteLine("*****************************");
/**
* YIELD KEYWORD
*/
//Syntactic sugar explanation
foreach (int i in Program.GetRandomNumbers(10))
{
Console.WriteLine("MY RANDOM NUMBER: " + i);
}
foreach (int i in HybridNumbers)
{
Console.WriteLine(i);
}
//Desugarized foreach loop
IEnumerable<int> Desugarized = HybridNumbers;
IEnumerator rator = HybridNumbers.GetEnumerator();
while (rator.MoveNext())
{
Console.WriteLine("Desugarized foreach loop!");
Console.WriteLine(rator.Current);
}
//Grouping
List<Customer> customers = new List<Customer>
{
new Customer { CustomerID="1", Country = "Poland", Name = "Tomek", Age = 21},
new Customer { CustomerID="2", Country = "Poland", Name = "Mateusz", Age = 18},
new Customer { CustomerID="3", Country = "Poland", Name = "Agata", Age = 27},
new Customer { CustomerID="4", Country = "UK", Name = "Raheel", Age = 25},
new Customer { CustomerID="5", Country = "UK", Name = "Luke", Age = 48},
new Customer { CustomerID="6", Country = "UK", Name = "Steve", Age = 77},
new Customer { CustomerID="7", Country = "Russia", Name = "Nikita", Age = 20},
new Customer { CustomerID="8", Country = "Argentina", Name = "Domminica", Age = 16},
new Customer { CustomerID="9", Country = "Argentina", Name = "RichBich", Age = 33},
new Customer { CustomerID="10", Country = "Israel", Name = "JesusChristus", Age = 600},
new Customer { CustomerID="11", Country = "Moldovia", Name = "Siergiej", Age = 40},
};
List<Order> orders = new List<Order>
{
new Order { OrderID=1, CustomerID="1", OrderDate=new DateTime(2020,10,1), ShipCountry="Malysia" },
new Order { OrderID=2, CustomerID="1", OrderDate=new DateTime(2020,10,3), ShipCountry="Malysia" },
new Order { OrderID=3, CustomerID="1", OrderDate=new DateTime(2020,10,17), ShipCountry="Malysia" },
new Order { OrderID=4, CustomerID="2", OrderDate=new DateTime(2020,10,22), ShipCountry="Malysia" },
new Order { OrderID=5, CustomerID="3", OrderDate=new DateTime(2020,10,5), ShipCountry="Malysia" },
new Order { OrderID=6, CustomerID="4", OrderDate=new DateTime(2020,10,4), ShipCountry="Malysia" },
new Order { OrderID=7, CustomerID="5", OrderDate=new DateTime(2020,10,4), ShipCountry="Malysia" },
new Order { OrderID=8, CustomerID="5", OrderDate=new DateTime(2020,10,9), ShipCountry="Malysia" },
new Order { OrderID=9, CustomerID="6", OrderDate=new DateTime(2020,10,10), ShipCountry="Malysia" },
new Order { OrderID=10, CustomerID="6", OrderDate=new DateTime(2020,10,24), ShipCountry="Malysia" },
new Order { OrderID=11, CustomerID="6", OrderDate=new DateTime(2020,10,25), ShipCountry="Malysia" },
new Order { OrderID=12, CustomerID="6", OrderDate=new DateTime(2020,10,11), ShipCountry="Malysia" },
new Order { OrderID=13, CustomerID="7", OrderDate=new DateTime(2020,10,13), ShipCountry="Malysia" },
new Order { OrderID=14, CustomerID="7", OrderDate=new DateTime(2020,10,14), ShipCountry="Malysia" },
new Order { OrderID=15, CustomerID="8", OrderDate=new DateTime(2020,10,2), ShipCountry="Malysia" },
new Order { OrderID=16, CustomerID="9", OrderDate=new DateTime(2020,10,8), ShipCountry="Malysia" },
new Order { OrderID=17, CustomerID="10", OrderDate=new DateTime(2020,10,5), ShipCountry="Malysia" },
new Order { OrderID=18, CustomerID="10", OrderDate=new DateTime(2020,10,30), ShipCountry="Malysia" },
new Order { OrderID=19, CustomerID="11", OrderDate=new DateTime(2020,10,1), ShipCountry="Malysia" },
new Order { OrderID=20, CustomerID="11", OrderDate=new DateTime(2020,10,2), ShipCountry="Malysia" },
new Order { OrderID=21, CustomerID="11", OrderDate=new DateTime(2020,10,4), ShipCountry="Malysia" }
};
foreach (Customer c in customers.OrderBy(c => c.Country))
{
Console.WriteLine(c.Country + ":" + c.Name);
}
var customersGroupedByCountry = customers.GroupBy(c => c.Country).OrderByDescending(g=>g.Count());
Console.WriteLine("Time for grouping: ");
foreach(IGrouping<string,Customer> g in customersGroupedByCountry)
{
Console.WriteLine("Group name: " + g.Key);
foreach(Customer c in g)
{
Console.WriteLine("Name: " + c.Name);
}
}
var useLetType =
from g in customersGroupedByCountry
//introduce variable to query
let count = g.Count()
orderby count descending
//Return new anon type
select new { Country = g.Key, NumCustomers = count };
var withoutLetKeyword =
customersGroupedByCountry.Select(g => new { g, NumCustomers = g.Count() })
.OrderBy(at => at.NumCustomers)
.Select(at => new { at.g.Key, at.NumCustomers });
//Introduce INTO keyword
//Selecting (Projecting) While Grouping
//purplemath.com QUADRATIC FORMULA
var selectingWhileGrouping=customers.GroupBy(g => new { g.Country }, g => g);
foreach(var g in selectingWhileGrouping)
{
Console.WriteLine(g.Key+": ");
foreach(Customer c in g)
{
Console.WriteLine(c.Name + ": " + c.Age);
}
}
//Let Clauses And Even Deeper Transparent Identifiers
var inputs = new[]
{
new { a=1, b=2, c=3 },
new { a=2, b=9, c=4 },
new{ a=7, b=3, c=6}
};
//Two approaches
//First
var roots =
from coef in inputs
let negB = -coef.b
let discriminant = coef.b * coef.b - 4 * coef.a * coef.c
let twoA = 2 * coef.a
select new
{
FirstRoot = (negB + discriminant) / twoA,
SecondRoot = (negB - discriminant) / twoA
};
//Second
var rootsByExtensions =
inputs
.Select(coef => new { coef, negB = -coef.b })
.Select(t1 => new { t1, discriminant = t1.coef.b * t1.coef.b - 4 * t1.coef.a * t1.coef.c })
.Select(t2 => new { t2, twoA = 2 * t2.t1.coef.a })
.Select(t3 => new { FirstRoot = (t3.t2.t1.negB + t3.t2.discriminant) / t3.twoA, SecondRoot = (t3.t2.t1.negB - t3.t2.discriminant) / t3.twoA });
//LINQ Joins
var customersWithOrders =
from c in customers
from o in orders
where c.CustomerID == o.CustomerID
select new { Customer = c, Order = o };
//Same results using join
var customersWithOrdersByJoin =
from c in customers
join o in orders
on c.CustomerID equals o.CustomerID
select new { c.Name, o.OrderDate };
//Use extensions method
var customersWithOrdersByExtensionMethods =
customers.Join(orders, c => c.CustomerID, o => o.CustomerID, (c, o) => new { c.Name, o.OrderDate });
foreach(var pair in customersWithOrdersByExtensionMethods)
{
Console.WriteLine("New pair: ");
Console.WriteLine(pair.Name+" : "+pair.OrderDate);
}
//LINQ Navigation Property [Entity framework]
//var firstCustomer = customers.First();
//Console.WriteLine("################## NAVI #################");
//foreach(Order o in firstCustomer.Orders)
//{
// Console.WriteLine("\t"+o.OrderDate);
//}
//Join and Group
var groupedByOrdersOrderedByClients =
from c in customers
join o in orders
on c.CustomerID equals o.CustomerID into g //this solution creating IEnumerable rather than IGroupable
//You can avoid grouping, use into instead
group o by c into g
let NumOrders = g.Count()
orderby NumOrders descending
select new { g.Key.Name, NumOrders };
foreach(var pair in groupedByOrdersOrderedByClients)
{
Console.WriteLine(pair.Name + " : " + pair.NumOrders);
}
}
static IEnumerable<int> GetRandomNumbers(int count)
{
GetRandomNumberClass ret = new GetRandomNumberClass();
ret.count = count;
return ret;
}
public static IEnumerable<int> Numbers
{
get
{
Console.WriteLine("Start");
Console.WriteLine("Return 3");
yield return 3;
Console.WriteLine("Return 5");
yield return 5;
Console.WriteLine("Return 66");
yield return 66;
Console.WriteLine("This blocked was called after last invocation of yield return - now it's finished");
}
}
public static IEnumerable<int> HybridNumbers
{
get { return new NumberHybrid(); }
}
class NumberHybrid : IEnumerable<int>, IEnumerator<int>
{
int state;
int current;
public int Current
{
get { return current; }
}
public bool MoveNext()
{
switch (state)
{
case 0:
Console.WriteLine("Start");
Console.WriteLine("Yield 3");
current = 3;
state = 1;
break;
case 1:
Console.WriteLine("Yield 5");
state = 2;
current = 5;
break;
case 2:
Console.WriteLine("Yield 13");
current = 13;
state = 3;
break;
case 3:
Console.WriteLine("End!");
return false;
}
return true;
}
object IEnumerator.Current
{
get { return Current; }
}
public IEnumerator<int> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Dispose()
{
}
public void Reset()
{
}
}
class GetRandomNumberClass : IEnumerable<int>, IEnumerator<int>
{
public int count;
public int i;
public int current;
int state;
public int Current
{
get { return current; }
}
public bool MoveNext()
{
switch (state)
{
//Initialization of for loop
case 0:
i = 0;
goto case 1;
case 1:
state = 1;
if (!(i < count))
return false;
current = Program.Random.Next();
state = 2;
return true;
case 2:
i++;
goto case 1;
}
return false;
}
object IEnumerator.Current
{
get { return Current; }
}
public IEnumerator<int> GetEnumerator()
{
//Return itself, cause this class implement IEnumerator interface
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
//It wont call itself recursively, at first it will looking for method which is not implemented explicitly
return GetEnumerator();
}
public void Reset(){}
public void Dispose() { }
}
}
}