码迷,mamicode.com
首页 > 其他好文 > 详细

Linq分组

时间:2015-11-05 22:15:59      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:

1.lin语句

 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);
                }
            }

 

  

Linq分组

标签:

原文地址:http://www.cnblogs.com/mawenzhu/p/4940743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!