Linq分组
1.lin语句
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 | int [] nums = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0, 3 }; DataTable table = new DataTable( "Numbers" ); table.Columns.Add( "number" , typeof ( int )); foreach ( int n in nums) { table.Rows.Add( new object [] { n }); } var numbers = table.AsEnumerable(); var numberGroups = from n in numbers group n by n.Field< int >( "number" ) into g select new { Remainder = g.Key, Numbers = g }; foreach ( var g in numberGroups) { Console.WriteLine( "Numbers with a remainder of {0} when divided by 5:" , g.Remainder); foreach ( var n in g.Numbers) { Console.WriteLine(n.Field< int >( "number" ) + ",count:" + g.Numbers.Count()); } }2.比较器 public void Method{ var anagrams = testDS.Tables[ "Anagrams" ].AsEnumerable(); var orderGroups = anagrams.GroupBy(w => w.Field< string >( "anagram" ).Trim(), new AnagramEqualityComparer()); foreach ( var g in orderGroups) { Console.WriteLine( "Key: {0}" , g.Key); foreach ( var w in g) { Console.WriteLine( "\t" + w.Field< string >( "anagram" )); } } } //创建一个比较器 private class AnagramEqualityComparer : IEqualityComparer< string > { public bool Equals( string x, string y) { return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode( string obj) { return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString( string word) { char [] wordChars = word.ToCharArray(); Array.Sort< char >(wordChars); return new string (wordChars); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步