|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace HelloDotNetGuide.CSharp语法 |
| 8 | +{ |
| 9 | + public class LinqExercise |
| 10 | + { |
| 11 | + #region .NET 9 中 LINQ 新增的功能 |
| 12 | + |
| 13 | + //public static void CountByExample() |
| 14 | + //{ |
| 15 | + // //这里wordCounts是一个字典,包含每个单词及其出现次数的键值对 |
| 16 | + // var sourceText = "This is a test text. This is only a test. This is the best. This,This,This"; |
| 17 | + // KeyValuePair<string, int> mostFrequentWord = sourceText |
| 18 | + // .Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries) |
| 19 | + // .Select(word => word.ToLowerInvariant()) |
| 20 | + // .CountBy(word => word) |
| 21 | + // .MaxBy(pair => pair.Value); |
| 22 | + |
| 23 | + // Console.WriteLine($"最常见的词是:'{mostFrequentWord.Key}' {mostFrequentWord.Value}"); |
| 24 | + //} |
| 25 | + |
| 26 | + //public static void AggregateByExample() |
| 27 | + //{ |
| 28 | + // (string id, int score)[] data = |
| 29 | + // [ |
| 30 | + // ("0", 88), |
| 31 | + // ("1", 5), |
| 32 | + // ("2", 4), |
| 33 | + // ("1", 10), |
| 34 | + // ("6", 5), |
| 35 | + // ("4", 10), |
| 36 | + // ("6", 25) |
| 37 | + // ]; |
| 38 | + |
| 39 | + // // aggregatedData 是一个序列,包含按姓名分组并计算总分的元素 |
| 40 | + // var aggregatedData = |
| 41 | + // data.AggregateBy( |
| 42 | + // keySelector: entry => entry.id, |
| 43 | + // seed: 0, |
| 44 | + // (totalScore, curr) => totalScore + curr.score |
| 45 | + // ); |
| 46 | + |
| 47 | + // foreach (var item in aggregatedData) |
| 48 | + // { |
| 49 | + // Console.WriteLine(item); |
| 50 | + // } |
| 51 | + //} |
| 52 | + |
| 53 | + //public static void IndexExample() |
| 54 | + //{ |
| 55 | + // var lines = new List<string> { "First line", "Second line", "Third line" }; |
| 56 | + // foreach (var (index, line) in lines.Index()) |
| 57 | + // { |
| 58 | + // Console.WriteLine($"Line {index + 1}: {line}"); |
| 59 | + // } |
| 60 | + //} |
| 61 | + |
| 62 | + #endregion |
| 63 | + } |
| 64 | +} |
0 commit comments