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);
                }
            }
复制代码
复制代码

 

  

posted on   马文柱  阅读(180)  评论(0编辑  收藏  举报

努力加载评论中...
点击右上角即可分享
微信分享提示