csharp: Linq keyword example

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
/// <summary>
    /// http://www.dotnetperls.com/linq
    /// </summary>
    public partial class LinqForm : Form
    {
 
        const int _max = 1000000;
        /// <summary>
        /// Linq keyword
        /// </summary>
       public enum  CheckLinq
        {
            Distinct,
            Union,
            Intersect,
            Except,
            Var,
            Loop,
            New,
            Orderby,
            Group,
            Join,
            Let,
            Where,
            ToDictionary,
            Lambda,
            GroupJoin,
            GroupBy
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
       DataTable setcom()
       {
           DataTable dt = new DataTable();
           dt.Columns.Add("id", typeof(int));
           dt.Columns.Add("name", typeof(string));
           dt.Rows.Add(1, "Distinct");
           dt.Rows.Add(2, "Union");
           dt.Rows.Add(3, "Intersect");
           dt.Rows.Add(4, "Except");
           dt.Rows.Add(5, "Var");
           dt.Rows.Add(6, "Loop");
           dt.Rows.Add(7, "New");
           dt.Rows.Add(8, "Orderby");
           dt.Rows.Add(9, "Group");
           dt.Rows.Add(10, "Join");
           dt.Rows.Add(11, "Let");
           dt.Rows.Add(12, "Where");
           dt.Rows.Add(13, "ToDictionary");
           dt.Rows.Add(14, "Lambda");
           dt.Rows.Add(15, "GroupJoin");
           dt.Rows.Add(16, "GroupBy");
 
           return dt;
       }
 
        /// <summary>
        ///
        /// </summary>
        public LinqForm()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LinqForm_Load(object sender, EventArgs e)
        {
            this.comboBox1.DataSource = setcom();
            this.comboBox1.ValueMember = "id";
            this.comboBox1.DisplayMember = "name";
 
        }
 
        /// <summary>
        ///
        /// </summary>
        public  string TestSetSemantics(CheckLinq check)
        {
            List<string> lstColumn = new List<string>();
            List<string> strDistinct = new List<string>();
            List<string> strUnion = new List<string>();
            List<string> strExcept = new List<string>();
            List<string> strIntersect = new List<string>();
            List<string> strVar = new List<string>();
            List<string> strLoop = new List<string>();
            List<string> strNew = new List<string>();
            List<string> strOrderby = new List<string>();
            List<string> strGroup = new List<string>();
            List<string> strJoin = new List<string>();
            List<string> strLet = new List<string>();
            List<string> strWhere = new List<string>();
            List<string> strToDictionary = new List<string>();
            List<string> strLambda = new List<string>();
            List<string> strGroupJoin = new List<string>();
            List<string> strGroupBy = new List<string>();
 
            string str = string.Empty;
            
            string[] dailySecurityLog = {
                   "Bob logged in",
                   "Bob logged out",
                   "Bob logged in",
                   "Bill logged in",
                   "Melissa logged in",
                   "Bob logged out",
                   "Bill logged out",
                   "Bill logged in",
                   "Tim logged in",
                   "Scott logged in",
                   "Scott logged out",
                   "Dave logged in",
                   "Tim logged out",
                   "Bob logged in",
                   "Dave logged out"};
 
            Employee[] project1 = {
                       new Employee(){ Name = "Bob" },
                       new Employee(){ Name = "Bill" },
                       new Employee(){ Name = "Melissa" },
                       new Employee(){ Name = "Shawn" } };
            Employee[] project2 = {
                       new Employee(){ Name = "Shawn" },
                       new Employee(){ Name = "Tim" },
                       new Employee(){ Name = "Scott" } };
            Employee[] project3 = {
                       new Employee(){ Name = "Bob" },
                       new Employee(){ Name = "Dave" },
                       new Employee(){ Name = "Tim" },
                       new Employee(){ Name = "Shawn" } };
            IEnumerable<string> whoLoggedIn =
                  dailySecurityLog.Where(logEntry => logEntry.Contains("logged in")).Distinct();
            var allProjectEmployees = project1.Union(project2.Union(project3));
 
            switch (check)
            {
                case CheckLinq.Distinct:
                    // Distinct
                    //"Everyone who logged in today:";
                    foreach (string who in whoLoggedIn)
                    {
                        strDistinct.Add(who);                      
                    }
                     str=String.Join(",",strDistinct.ToArray()); //结果:Bob logged in,Bill logged in,Melissa logged in,Tim logged in,Scott logged in,Dave logged in
                    break;
                case CheckLinq.Union:
                    // Union
                    //"Employees for all projects:";                   
                    foreach (Employee employee in allProjectEmployees)
                    {                      
                        strUnion.Add(employee.Name);
 
                    }
                    str = String.Join(",",strUnion.ToArray());  //结果:Bob,Bill,Melissa,Shawn,Tim,Scott,Dave
                    break;
                case CheckLinq.Intersect:
                    // Intersect
                    //"Employees on every project:";
 
                    var everyProjectEmployees = project1.Intersect(project2.Intersect(project3));
                    foreach (Employee employee in everyProjectEmployees)
                    {
                        strIntersect.Add(employee.Name);
                    }
                    str = String.Join(",",strIntersect.ToArray()); //结果:Shawn
                    break;
                case CheckLinq.Except:
 
                    // Except
                    var intersect1_3 = project1.Intersect(project3);
                    var intersect1_2 = project1.Intersect(project2);
                    var intersect2_3 = project2.Intersect(project3);
                    var unionIntersect = intersect1_2.Union(intersect1_3).Union(intersect2_3);
 
                    //"Employees on only one project:";
                    var onlyProjectEmployees = allProjectEmployees.Except(unionIntersect);
                    foreach (Employee employee in onlyProjectEmployees)
                    {
                        strExcept.Add(employee.Name);
                    }
                    str = String.Join(",",strExcept.ToArray()); //结果:Bill,Melissa,Scott,Dave
                    break;
                case CheckLinq.Var:
                    int[] array = { 1, 2, 3, 6, 7, 8 };
                    // Query expression.
                    var elements = from element in array
                               orderby element descending
                               where element > 2
                               select element;
                    // Enumerate.
                    foreach (var element in elements)
                    {
                        strVar.Add(element.ToString());                    
                    }
                    str = String.Join(",", strVar.ToArray());
                    break;
                case CheckLinq.Loop:
                    int[] values = { 10, 0, 1, 1, 20, 300, 400, 4 };
                    // Version 1: use LINQ.
                    var s1 = Stopwatch.StartNew();
                    for (int i = 0; i < _max; i++)
                    {
                        int count = CountLinq(values);
                    }
                    s1.Stop();
 
                    // Version 2: use for-loop.
                    var s2 = Stopwatch.StartNew();
                    for (int i = 0; i < _max; i++)
                    {
                        int count = CountFor(values);
                    }
                    s2.Stop();
                    strLoop.Add(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
                        _max).ToString("0.00 ns"));
                    strLoop.Add(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
                        _max).ToString("0.00 ns"));
                    str = String.Join(",", strLoop.ToArray());
                    break;
                case CheckLinq.New:
                        string[] newarray = { "one", "two", "three", "four", "", "seven" };
                        // Use Select New.
                        var result = from newelement in newarray
                                     select new { Value = newelement, Id = Id(newelement) };
 
                        foreach (var anonymous in result)
                        {
                            string value = anonymous.Value;
                            int id = anonymous.Id;
                            strNew.Add(anonymous.ToString());
                        }
                        str = String.Join(",", strNew.ToArray());
                    break;
                case CheckLinq.Orderby:
                    // Input array.
                    int[] orderarray = { 2, 5, 3 };
                    // Use orderby, orderby ascending, and orderby descending.
                    var result0 = from orderelement in orderarray
                                  orderby orderelement
                                  select orderelement;
 
                    var result1 = from orderelement in orderarray
                                  orderby orderelement ascending
                                  select orderelement;
 
                    var result2 = from orderelement in orderarray
                                  orderby orderelement descending
                                  select orderelement;
                    // Print results.
                    strOrderby.Add("result0:");
                    foreach (var orderelement in result0)
                    {
                        strOrderby.Add(orderelement.ToString());
                    }
                    strOrderby.Add("result1:");
                    foreach (var orderelement in result1)
                    {
                        strOrderby.Add(orderelement.ToString());
                    }
                    strOrderby.Add("result2:");
                    foreach (var orderelement in result2)
                    {
                        strOrderby.Add(orderelement.ToString());
                    }
                    str = String.Join(",", strOrderby.ToArray());
                    break;
                case CheckLinq.Group:
                    // Input array.
                    int[] grouparray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
                    // Group elements by IsEven.
                    var groupresult = from groupelement in grouparray
                                      orderby groupelement
                                      group groupelement by IsEven(groupelement);
 
                    // Loop over groups.
                    foreach (var group in groupresult)
                    {
                        // Display key and its values.
                        strGroup.Add(group.Key.ToString());
                        foreach (var value in group)
                        {
                            strGroup.Add(value.ToString());
                        }
                    }
                    str = String.Join(",", strGroup.ToArray());
                    break;
                case CheckLinq.Join:
                       // Example customers.
                       var customers = new Customer[]
                        {
                            new Customer{ID = 5, Name = "Sam"},
                            new Customer{ID = 6, Name = "Dave"},
                            new Customer{ID = 7, Name = "Julia"},
                            new Customer{ID = 8, Name = "Sue"}
                        };
 
                                        // Example orders.
                                        var orders = new Order[]
                        {
                            new Order{ID = 5, Product = "Book"},
                            new Order{ID = 6, Product = "Game"},
                            new Order{ID = 7, Product = "Computer"},
                            new Order{ID = 8, Product = "Shirt"}
                        };
 
                    // Join on the ID properties.
                    var query = from c in customers
                                join o in orders on c.ID equals o.ID
                                select new { c.Name, o.Product };
 
                     
                    // Display joined groups.
                    foreach (var group in query)
                    {
                        strJoin.Add(string.Format("{0} bought {1}", group.Name, group.Product));
                    }
                    str = String.Join(",", strJoin.ToArray());
                    break;
                case CheckLinq.Let:
                    int[] letarray = { 0, 1, 2 };
                    // Build IEnumerable of Analyze arguments and its return values.
                    var letresult = from letelement in letarray
                                    let v = Analyze(letelement)
                             let x = Analyze(v)
                             select new { v, x };
                    // This prints argument, return value pairs.
                    foreach (var letelement in letresult)
                    {
                        strLet.Add(letelement.ToString());
                    }
                    str = String.Join(",", strLet.ToArray());
 
                    break;
                case CheckLinq.Where:
                    //
                    // Example array that contains unwanted null and empty strings.
                    //
                    string[] wherearray = { "dot", "", "net", null, null, "perls", null };
                    //
                    // Use Where method to remove null strings.
                    //
                    strWhere.Add("Begins output from first loop:");
                    var whreresult1 = wherearray.Where(item => item != null);
                    foreach (string value in whreresult1)
                    {
                        strWhere.Add(value);
                    }
                    //
                    // Use Where method to remove null and empty strings.
                    //
                    strWhere.Add("Begins output from second loop:");
                    var whrereresult2 = wherearray.Where(item => !string.IsNullOrEmpty(item));
                    foreach (string value in whrereresult2)
                    {
                        strWhere.Add(value);
                    }
                    str = String.Join(",", strWhere.ToArray());
 
                    break;
                case CheckLinq.ToDictionary:
                    // Example with strings and List.
                    List<string> list = new List<string>()
                    {
                        "cat",
                        "dog",
                        "animal"
                    };
                    var animals = list.ToDictionary(x => x, x => true);
                    if (animals.ContainsKey("dog"))
                    {
                        // This is in the Dictionary.
                        strToDictionary.Add("dog exists");
                    }
                    str = String.Join(",", strToDictionary.ToArray());//结果:dog exists
                    break;
                case CheckLinq.Lambda:
                    List<int> lamelements = new List<int>() { 10, 20, 31, 40 };
                    // ... Find index of first odd element.
                    int oddIndex = lamelements.FindIndex(x => x % 2 != 0);  //
                         strLambda.Add(oddIndex.ToString());
                    str = String.Join(",", strLambda.ToArray());//结果:31 index: 2
                    break;
                case CheckLinq.GroupJoin:
                    // Example customers.
                    var gcustomers = new Customer[]
                    {
                        new Customer{Code = 5, Name = "Sam"},
                        new Customer{Code = 6, Name = "Dave"},
                        new Customer{Code = 7, Name = "Julia"},
                        new Customer{Code = 8, Name = "Sue"}
                    };
 
                    // Example orders.
                    var gorders = new Order[]
                    {
                        new Order{KeyCode = 5, Product = "Book"},
                        new Order{KeyCode = 6, Product = "Game"},
                        new Order{KeyCode = 7, Product = "Computer"},
                        new Order{KeyCode = 7, Product = "Mouse"},
                        new Order{KeyCode = 8, Product = "Shirt"},
                        new Order{KeyCode = 5, Product = "Underwear"}
                    };
 
                    // Correlate "customers" with "orders"
                    // ... Use Code property as key for Customer.
                    // ... Use KeyCode property as key for Order.
                    // ... For each result, create object with Name and IEnumerable of orders.
                    var gquery = gcustomers.GroupJoin(gorders,
                        c => c.Code,
                        o => o.KeyCode,
                        (c, gresult) => new Result(c.Name, gresult));
 
                    // Enumerate results.                   
                    foreach (var gresult in gquery)
                    {
                        string gj = string.Empty;
                        List<string> gp = new List<string>();
                        gj=string.Format("{0} bought...", gresult.Name);
                        foreach (var item in gresult.Collection)
                        {
                           gp.Add(item.Product);
                        }
                        gj = gj + String.Join(",",gp.ToArray());
                        strGroupJoin.Add(gj);
                        gj = "";
                    }
                    str = String.Join(";", strGroupJoin.ToArray()); //结果:Sam bought...Book,Underwear;Dave bought...Game;Julia bought...Computer,Mouse;Sue bought...Shirt
                    break;
                case CheckLinq.GroupBy:
                    // Input array.
                    int[] gyarray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                    // Group elements by IsEven.
                    var gyresult = gyarray.GroupBy(a => IsEven(a));
                    // Loop over groups.
                    foreach (var group in gyresult)
                    {
                        string gb = string.Empty;
                        // Display key for group.
                        gb=string.Format("IsEven = {0}:", group.Key);
 
                        List<string> gbv = new List<string>();
                        // Display values in group.
                        foreach (var value in group)
                        {
                            gbv.Add(string.Format("{0} ", value));
                        }
                        gb =gb+ String.Join(",", gbv.ToArray());
                        // End line.
                        strGroupBy.Add(gb);
                        gb = "";
                    }
                    str = String.Join(";", strGroupBy.ToArray()); //结果:IsEven = False:1 ,3 ,5 ,7 ,9 ;IsEven = True:2 ,4 ,6 ,8
                    break;
                default:
                    str = "";
                    break;                 
 
            }
            return str;
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        int CountLinq(int[] values)
        {
            // Count values greater than or equal to 10 with LINQ.
            return (from x in values
                    where x >= 10
                    select x).Count();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        int CountFor(int[] values)
        {
            // Count values greater than or equal to 10 with a loop.
            int count = 0;
            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] >= 10)
                {
                    count++;
                }
            }
            return count;
        }
 
         int _value;
        /// <summary>
        ///
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
         int Id(string element)
        {
            // Get Id.
            return string.IsNullOrEmpty(element) ?
                0 :
                _value++;
        }
         /// <summary>
         /// 奇数偶数
         /// </summary>
         /// <param name="value"></param>
         /// <returns></returns>
         bool IsEven(int value)
         {
             return value % 2 == 0;
         }
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
         int Analyze(int value)
         {
             // Return a value for each argument.
             switch (value)
             {
                 case 0:
                     return 1;
                 case 1:
                     return 2;
                 case 2:
                 default:
                     return 3;
             }
         }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            int c = (int)this.comboBox1.SelectedValue;
            switch (c)
            {
                case 1:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Distinct);
                    break;
                case 2:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Union);
                    break;
                case 3:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Intersect);
                    break;
                case 4:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Except);
                    break;
                case 5:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Var);
                    break;
                case 6:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Loop);
                    break;
                case 7:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.New);
                    break;
                case 8:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Orderby);
                    break;
                case 9:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Group);
                    break;
                case 10:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Join);
                    break;
                case 11:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Let);
                    break;
                case 12:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Where);
                    break;
                case 13:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.ToDictionary);
                    break;
                case 14:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.Lambda);
                    break;
                case 15:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.GroupJoin);
                    break;
                case 16:
                    this.textBox1.Text = TestSetSemantics(CheckLinq.GroupBy);
                    break;
                default:
                    this.textBox1.Text = "";
                    break;
            }
        }
    }
 
 
    class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Code { get; set; }
    }
 
    class Order
    {
        public int ID { get; set; }
        public string Product { get; set; }
        public int KeyCode { get; set; }
    }
 
    class Result
    {
        public string Name { get; set; }
        public IEnumerable<Order> Collection { get; set; }
        public Result(string name, IEnumerable<Order> collection)
        {
            this.Name = name;
            this.Collection = collection;
        }
    }
 
 /// <summary>
    ///
    /// </summary>
    public class Employee
    {
        /// <summary>
        ///
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return this.Name;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            return this.GetHashCode().Equals(obj.GetHashCode());
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return this.Name.GetHashCode();
        }
    }

  

posted @   ®Geovin Du Dream Park™  阅读(431)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示